我的下图中有3个子图。我为每个子图设置宽度为0.3,但现在条的大小不均匀。如何使条形尺寸相同,并保持条形对之间的间距?
我的代码:
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()
答案 0 :(得分:0)
如果所有子图都应该具有相同的大小,那么想法是设置xaxis的限制,使所有条都具有相同的宽度。
ax.set_xlim(-0.5,maxn-0.5)
其中maxn
是要绘制的最大条形数。
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()