2017-03-01 49 views
0

我正在循環包含6個col_names的列表。我一次循環3次,所以我可以在每次迭代後打印3個子圖。 我有2個數據幀具有相同的列名,所以除了每個列名的直方圖外,它們看起來相同。熊貓將多個相同x軸的子圖組合成1條形圖

我想在同一個子圖上繪製兩個數據幀的相似列名。現在,我們將他們的直方圖繪製在2個獨立的子圖上。

目前,對於df_plot山口 'A', 'B', 'C':

enter image description here

以及用於df_plot2山口 'A', 'B', 'C': enter image description here

我只想要3個圖表,我可以將相似的列名稱組合到相同的圖表中,因此在同一圖表中有藍色和黃色條形。

添加df_plot2下面不工作。我想即時沒有正確定義我的第二個axs,但我不知道該怎麼做。

col_name_list = ['A','B','C','D','E','F'] 
chunk_list = [col_name_list[i:i + 3] for i in xrange(0, len(col_name_list), 3)] 
    for k,g in enumerate(chunk_list): 
     df_plot = df[g] 
     df_plot2 = df[g][df[g] != 0] 

     fig, axs = plt.subplots(1,len(g),figsize = (50,20)) 
     axs = axs.ravel() 

     for j,x in enumerate(g): 
      df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j], position=0, title = x, fontsize = 30) 
      # adding this doesnt work. 
      df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j], position=1, fontsize = 30) 
       axs[j].title.set_size(40) 
     fig.tight_layout() 

回答

0

的解決方案是繪製在同ax

變化axs[j] to axs

for k,g in enumerate(chunk_list): 
    df_plot = df[g] 
    df_plot2 = df[g][df[g] != 0] 

    fig, axs = plt.subplots(1,len(g),figsize = (50,20)) 
    axs = axs.ravel() 

    for j,x in enumerate(g): 
     df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs, position=0, title = x, fontsize = 30) 
     # adding this doesnt work. 
     df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs, position=1, fontsize = 30) 
      axs[j].title.set_size(40) 
    fig.tight_layout() 

然後就叫plt.plot()

Example this will plot x and y on the same subplot:

import matplotlib.pyplot as plt 
x = np.arange(0, 10, 1) 
y = np.arange(0, 20, 2) 

ax = plt.subplot(1,1) 
fig = plt.figure() 
ax = fig.gca() 
ax.plot(x) 
ax.plot(y) 

plt.show() 

編輯:

現在有一個擠壓關鍵字參數。這可以確保結果始終是一個2D numpy數組。

fig, ax2d = subplots(2, 2, squeeze=False) 

如果需要打開該成一維數組很簡單:

axli = ax1d.flatten() 
+0

我得到這個錯誤:'「numpy.ndarray」對象有沒有屬性「get_figure'' – jxn

+0

使用擠壓參數爲錯誤。 – SerialDev

+0

對不起,你能在我的例子中演示如何做到這一點? – jxn