我正试图为df中的“类别”列中的每一个类别绘制一个海运图。有7个独特的类别。我成功地做到了一排,但地块太小了。我想把它们排成两排(4排在第一排,3排在第七排)。除了应该将子图的参数更改为(2,4)之外,我应该如何更改代码?
fig, ax = plt.subplots(1, 7)
for i,g in enumerate(df.Category.unique()):
dfx = df[df['Category'] == g]
sns.set(style="whitegrid", rc={'figure.figsize':(28,6)})
sns.barplot(x = dfx['Month'], y = dfx['measure'], ci = None, label = g, ax=ax[i])
ax[i].legend(loc = 'lower center')
plt.tight_layout()
plt.show()发布于 2018-11-24 23:56:16
您可以在扁平的轴数组上循环,也可以使用groupby简化事情。因此,我认为代码可以是这样的(未经测试,因为问题中没有提供数据):
sns.set(style="whitegrid")
fig, axes = plt.subplots(2, 4)
for (n, dfx), ax in zip(df.groupby("Category"), axes.flat):
sns.barplot(x = dfx['Month'], y = dfx['measure'], ci = None, label = n, ax=ax)
ax.legend(loc = 'lower center')
axes[1,3].axis("off")
plt.tight_layout()
plt.show()此外,由于您似乎在使用海运,所以可以考虑使用seaborn.FacetGrid。这看起来就像
sns.set(style="whitegrid")
g = sns.FacetGrid(data=df, col = "Category", col_wrap=4)
g.map(sns.barplot, "Month", "measure")
plt.tight_layout()
plt.show()https://stackoverflow.com/questions/53463255
复制相似问题