简体   繁体   中英

Rotate existing axis tick labels in Matplotlib

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?

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

for ax in [ax1,ax2,ax3]:
    for label in ax.get_xticklabels():
        label.set_rotation(90) 
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.

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 s_ax in ax:
  s_ax.xaxis.set_tick_params(rotation=90)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM