2017-03-02 67 views
0

我在下圖中有3個子圖。我將每個子圖的寬度設置爲0.3,但是現在棒的大小不均勻。我如何使酒吧相同的大小,並保持兩對酒吧之間的間距?Matplotlib將酒吧的寬度設置爲所有子圖的相同大小

我的代碼:

g=['col1','col2','col3'] 
    fig, axs = plt.subplots(1,len(g)/1,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 = 'mytitle', fontsize = 30, width=0.3) 
     df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 1, color='red', width=0.3) 
     axs[j].title.set_size(40) 
     fig.tight_layout() 

enter image description here

+0

你可能想看看[這個問題](http://stackoverflow.com/questions/42191668/matplotlib-dynamic-bar-chart-height-based-on-data/ 42192931)。鑑於此,可以更精確地指定要求。例如。這些小區應該保持其大小,還是應該適應酒吧的規模? – ImportanceOfBeingErnest

+0

我可以改變小區尺寸來適應相似的條寬,但小區尺寸必須相同3 – jxn

回答

0

如果所有次要情節應該具有相同的大小,這個想法是設置x軸的限制,使得所有的酒吧具有相同的寬度。

ax.set_xlim(-0.5,maxn-0.5) 

其中maxn是酒吧的最大數量繪製。

enter image description here

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

col1 = np.random.choice(["Mon", "Tue", "Wed", "Thu", "Fri"], 100, p=[0.1, 0.4, 0.2, 0.2,0.1]) 
col2 = np.random.choice([0,1], 100, p=[0.4, 0.6]) 
col3 = np.random.choice(list("abcde"), 100, p=[0.15, 0.35, 0.1, 0.3,0.1]) 
df = pd.DataFrame({'col1':col1,'col2':col2,'col3':col3}) 


g=['col1','col2','col3'] 
fig, axs = plt.subplots(1,len(g)/1,figsize = (10,4)) 
axs = axs.ravel() 

maxn = 5 
for j,x in enumerate(g): 
    df[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 0, title = 'mytitle', width=0.3) 
    df[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 1, color='red', width=0.3) 
    axs[j].set_xlim(-0.5,maxn-0.5) 

fig.tight_layout() 
plt.show() 
相關問題