Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 thing happens with the legend it doesn't get resized if the windows is resized.

Is there a setting for that ?

like image 998
IordanouGiannis Avatar asked Nov 18 '11 12:11

IordanouGiannis


People also ask

How do I resize a title in Matplotlib?

In matplotlib, the size of the title can be adjusted by changing the values of the rcParams dictionary. We can change the default settings of 'rc' that are stored in a global dictionary to change its font size. Here we define a parameter dictionary to change the font size of the title.


1 Answers

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

like image 173
Joe Kington Avatar answered Sep 30 '22 04:09

Joe Kington