2017-02-21 182 views
2

我有这样一个数据帧:如何通过add_subplot添加子图后共享坐标轴?

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))  

    A B C D 
a 0.3 0.1 0.2 0.6 
b 0.2 0.0 0.5 0.3 
c 0.5 0.3 0.0 0.4 
d 0.2 0.1 0.7 0.6 

现在我要绘制每一行作为barplot由此y轴和x蜱标签使用add_subplot共享。

到现在为止,我只能产生一个情节,看起来像这样: enter image description here

有一个问题:

轴未共享,使用add_subplot以后怎么一个做到这一点? Here,这个问题通过创建一个巨大的子图来解决;有没有办法以不同的方式做到这一点?

我期望的结果看起来像上面的情节,唯一的区别是上面一行没有x-tick-labels,右面没有y-tick-labels。

我现在尝试以下操作:

import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) 

fig = plt.figure() 
bar_width = 0.35 
counter = 1 
index = np.arange(df.shape[0]) 

for indi, rowi in df.iterrows(): 

    ax = fig.add_subplot(2, 2, counter) 
    ax.bar(index, rowi.values, width=bar_width, tick_label=df.columns) 
    ax.set_ylim([0., 1.]) 
    ax.set_title(indi, fontsize=20) 
    ax.set_xticks(index + bar_width/2) 
    counter += 1 

plt.xticks(index + bar_width/2, df.columns) 
+1

你的意思是*共享*在'add_subplot(...,sharex =,sharey =)'? – kazemakase

+1

@kazemakase:如果'add_subplot'中存在'sharex =','sharey ='这些标志,那确实是完美的。但我没有看到这样的标志。 – Cleb

+1

你试过了吗?或者你只是说他们不存在,因为你太懒惰了? – ImportanceOfBeingErnest

回答

1

如何产生共同的次要情节在matplotlib的问题:

还有甚么可能这里有趣的是,你还可以直接使用在熊猫一行创建情节:

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd')) 
df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True) 
plt.show() 

enter image description here

相关问题