Skip to content Skip to sidebar Skip to footer

How Do I Autosize Text In Matplotlib Python?

I have a plot in matplotlib,and my problem is that because the x axe has strings as values when the plot window gets resized they overlap and they can't be read clearly. A similar

Solution 1:

Not exactly. (Have a look at the new matplotlib.pyplot.tight_layout() function for something vaguely similar, though...)

However, the usual trick with long x-tick labels is just to rotate them.

For example, if we have something with overlapping xticklabels:

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [15 * repr(i) for i in range(10)]
plt.xticks(range(10), labels)
plt.show()

enter image description here

We can rotate them to make them easier to read: (The key is the rotation=30. The call to plt.tight_layout() just adjusts the bottom margin of the plot so that the labels don't go off the bottom edge.)

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [10 * repr(i) for i in range(10)]
plt.xticks(range(10), labels, rotation=30)
plt.tight_layout()
plt.show()

enter image description here

By default, the tick labels are centered on the tick. For rotated ticks it often makes more sense to have the left or right edge of the label start at the tick.

For example, something like this (right side, positive rotation):

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [10 * repr(i) for i in range(10)]
plt.xticks(range(10), labels, rotation=30, ha='right')
plt.tight_layout()
plt.show()

enter image description here

Or this (left side, negative rotation):

import matplotlib.pyplot as plt

plt.plot(range(10))
labels = [10 * repr(i) for i in range(10)]
plt.xticks(range(10), labels, rotation=-30, ha='left')
plt.tight_layout()
plt.show()

enter image description here


Post a Comment for "How Do I Autosize Text In Matplotlib Python?"