Chris
Chris

Reputation: 13660

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?

Upvotes: 4

Views: 10579

Answers (4)

Rmobdick
Rmobdick

Reputation: 436

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)

Upvotes: 5

hui chen
hui chen

Reputation: 1074

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

Upvotes: 0

CPBL
CPBL

Reputation: 4030

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) 

Upvotes: 8

onur güngör
onur güngör

Reputation: 715

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.

Upvotes: 2

Related Questions