Rotate Axis Text in Python Matplotlib

Rotate Matplotlib x-axis label text

Based on the documentation set_xlabel accepts text arguments, of which rotation is one.

The example I used to test this is shown below, though .

import matplotlib.pyplot as plt
import numpy as np

plt.plot()
plt.gca().set_xlabel('Test', rotation='vertical')

How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?

The labels are centered at the tickmark position. Their bounding boxes are unequal in width and might even overlap, which makes them look unequally spaced.

Sample Image

Since you'd always want the ticklabels to link to their tickmarks, changing the spacing is not really an option.

However you might want to align them such the the upper right corner is the reference for their positioning below the tick.

Use the horizontalalignment or ha argument for that and set it to "right":

ax.set_xticklabels(xticklabels, rotation = 45, ha="right")

This results in the following plot:

Sample Image

An alternative can be to keep the ticklabels horizontally centered, but also center them vertically. This leads to an equal spacing but required to further adjust their vertical position with respect to the axis.

ax.set_xticklabels(xticklabels, rotation = 45, va="center", position=(0,-0.28))

Sample Image


Sample Image

The above can be used if the ticks are specified manually like in the question (e.g. via plt.xticks or via ax.set_xticks) or if a categorical plot is used.

If instead the labels are shown automatically, one should not use set_xticklabels. This will in general let the labels and tick positions become out of sync, because set_xticklabels sets the formatter of the axes to a FixedFormatter, while the locator stays the automatic AutoLocator, or any other automatic locator.

In those cases either use plt.setp to set the rotation and alignment of existing labels,

plt.setp(ax.get_xticklabels(), ha="right", rotation=45)

or loop over them to set the respective properties,

for label in ax.get_xticklabels():
label.set_ha("right")
label.set_rotation(45)

An example would be

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

t = np.arange("2018-01-01", "2018-03-01", dtype="datetime64[D]")
x = np.cumsum(np.random.randn(len(t)))

fig, ax = plt.subplots()
ax.plot(t, x)

for label in ax.get_xticklabels():
label.set_ha("right")
label.set_rotation(45)

plt.tight_layout()
plt.show()

Rotate Axis for matplotlib Annotate text : python

Additional arguments to the .annotate()-method are passed to Text, so you can do e.g.:

for i,txt in enumerate(date_match_df['service_name_'].tolist()):
print(txt)
axess.annotate(txt,(mdates.date2num(idx2[i]),stock2[i]), ha='left', rotation=60)

Where the change from your code is the addition of ha='left', rotation=60 in the end.

Matplotlib: Rotate x-axis tick labels when don't know x-axis value variable

When you set x ticks labels with df_corr.columns you are using data's columns, which are 4 ('index', 'label_h1', 'label_h2', 'label_h3'), for only three boxes, so you should discard 'index' column:

ax.set_xticklabels([label for label in df.columns if label != 'index'],rotation = 90)

In alternative, as explained by Jody Klymak in the comment below, you can use a easier way with:

ax.tick_params(which='major', labelrotation=90)

Complete code

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_csv(r'data/data.csv')

fig, ax = plt.subplots(1,1, figsize=(13,10), dpi= 80)

sns.boxplot(data=df, ax = ax)

ax.tick_params(which='major', labelrotation=90)
ax.set_yscale("log")

plt.show()

Sample Image

Rotate x axis labels in Matplotlib parasite plot

There are two ways to produce parasite axes:

  • Using the mpl_toolkits axisartist and axes_grid1 package, examples are

    • demo_parasite_axes
    • demo_parasite_axes2
    • this stackoverflow answer
  • Using usual subplots and their spines. Examples are

    • multiple_yaxis_with_spines
    • this stackoverflow answer

Here you are using the first approach, which may be a bit unintuitive due to it using the special axes provided by the axisartist toolkit.

Solution 1:

Use the usual subplots approach for which all the usual ways of rotating ticklabels work just fine, e.g.

plt.setp(ax.get_xticklabels(), rotation=90)

Solution 2:

In case you want to stick with the mpl_toolkits approach you need to obtain the ticklabels from the axis via axis["right"].major_ticklabels,

plt.setp(par2.axis["bottom"].major_ticklabels, rotation=-135)


Related Topics



Leave a reply



Submit