2017-02-21 181 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

相關問題