How to change text justification in Matplotlib labels?

Viewed 1141

I have made a graph in Matplotlib and want to change the justification of my rotated y-axis label.

In this code example, the text "This is an example plot" should be justified left.

import matplotlib.pyplot as plt
figure, axes = plt.subplots()
axes.plot([0, 1], [0, 1])
axes.set_ylabel('This is an\nexample plot', rotation=0)
axes.yaxis.set_label_coords(0.1, 0.9)
plt.show()

plot figure with a label with centered text

2 Answers

Matplotlib text commands, such as for labels and annotations, support a number of keyword arguments that affect alignment, orientation, spacing, font, etc. The full list of text properties can be found in the documentation. In the above example

axes.set_ylabel('This is an\nexample plot', rotation=0, horizontalalignment='left')

would do the trick.

As noted in the other answer, this particular example is an abuse of the y-axis label. But the general principle is the same for all kinds of Matplotlib labels.

I wouldn't manipulate the ylabel this way. Instead just put some text at the location you want.

import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
    
figure, axes = plt.subplots()
axes.plot([0, 1], [0, 1])
    
axes.add_artist(AnchoredText('This is an\nexample plot', "upper left", frameon=False))
    
plt.show()

plot with text anchored in top left corner

Related