8

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 ?

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Joe, what if I don't want any numbers AND win back the space, so that the canvas produced have no margins, just the square (ideally just the graphic, no lines) ? I'm trying to display it in a gtk container, and I need it precisely positioned. a.axis('off') just removes the numbers, and a.margins(0, tight=True) seems inoperant... Help!
@xaccrocheur - ax.margins controls how autoscaling the data limits works, not the "ouside" margins of the plot. If you want to control how much of the canvas the axes takes up, either 1) manually make an axes that takes up the entire figure by using ax = fig.add_axes([0, 0, 1, 1]), or 2) use subplots_adjust to change the "outside" margins of your subplots (e.g. fig.subplots_adjust(0, 0, 1, 1))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.