pandas 在 Matplotlib 中旋转现有轴标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28931022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:01:44  来源:igfitidea点击:

Rotate existing axis labels in Matplotlib

pythonpandasmatplotlib

提问by Chris

I start with tree plots:

我从树图开始:

df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])

fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)

ax1.barh(np.arange(len(df)),df['mean'].values, align='center')
ax2.barh(np.arange(len(df)),df['size'].values, align='center')
ax3.barh(np.arange(len(df)),df['stat'].values, align='center')

Is there a way to rotate the x axis labels on all three plots?

有没有办法在所有三个图上旋转 x 轴标签?

回答by CPBL

When you're done plotting, you can just loop over each xticklabel:

完成绘图后,您可以循环遍历每个 xticklabel:

for ax in [ax1,ax2,ax3]:
    for label in ax.get_xticklabels():
        label.set_rotation(90) 

回答by onur güng?r

df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])

fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)

plt.subplot(1,3,1)
barh(np.arange(len(df)),df['mean'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,2)
barh(np.arange(len(df)),df['size'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,3)
barh(np.arange(len(df)),df['stat'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")

Should do the trick.

应该做的伎俩。

回答by Rmobdick

You can do it for each ax your are creating:

您可以为正在创建的每个斧头执行此操作:

ax1.xaxis.set_tick_params(rotation=90)
ax2.xaxis.set_tick_params(rotation=90)
ax3.xaxis.set_tick_params(rotation=90)

or you do it inside a for before showing the plot if you are building your axs using subplots:

或者,如果您使用子图构建轴,则在显示图之前在 for 中执行此操作:

for s_ax in ax:
  s_ax.xaxis.set_tick_params(rotation=90)

回答by hui chen

Here is another more generic solution: you can just use axes.flatten() which will provide you with much more flexibility when you have higher dimensions.

这是另一个更通用的解决方案:您可以只使用axes.flatten(),当您有更高的维度时,它将为您提供更大的灵活性。

for i, ax in enumerate(axes.flatten()):

for i, ax in enumerate(axes.flatten()):

sns.countplot(x= cats.iloc[:, i], orient='v', ax=ax)
for label in ax.get_xticklabels():
    # only rotate one subplot if necessary.
    if i==3:
        label.set_rotation(90)

fig.tight_layout()

fig.tight_layout()