在 Matplotlib 中旋转现有轴刻度标签

Rotate existing axis tick labels in Matplotlib

我从树图开始:

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')

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

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")

应该可以解决问题。

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

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

这是另一个更通用的解决方案:你可以只使用 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()

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

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

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

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