rotating xticks causes the ticks to be partially hidden

Question:

I am creating a plot with names on x axis and time values(minutes) on y axis.The names on x axis are like

['cooking']18:15:27 ,['study']18:09:19,['travel']18:21:34` etc ..

where as the y values are 5,1,1 etc.I have given xlabel as ‘categories’ and ylabel as ‘durations in minutes’.

Since the xticks were strings of some length,I decided to rotate them by 90 to avoid overlapping.Now ,the ticks are partially hidden and the xlabel has disappeared.

plot where xticks get partially hidden and xlabel disappears

Is there some way I can make the whole plot accommodate everything..?

here is the code snippet

import matplotlib.pyplot as plt

figure = plt.figure()
barwidth = 0.25
ystep = 10
plt.grid(True)
plt.xlabel('categories')
plt.ylabel('durations in  minutes')
plt.title('durations for categories-created at :'+now)
plt.bar(xdata, ydata, width=barwidth,align='center')
plt.xticks(xdata,catnames,rotation=90)
plt.yticks(range(0,maxduration+ystep,ystep))
plt.xlim([min(xdata) - 0.5, max(xdata) + 0.5])
plt.ylim(0,max(ydata)+ystep)
figure.savefig("myplot.png",format="png")
Asked By: markjason72

||

Answers:

One good option is to rotate the tick labels.

In your specific case, you might find it convenient to use figure.autofmt_xdate() (Which will rotate the x-axis labels among other things).

Alternatively, you could do plt.setp(plt.xticks()[1], rotation=30) (or various other ways of doing the same thing).

Also, as a several year later edit, with recent versions of matplotlib, you can call fig.tight_layout() to resize things to fit the labels inside the figure, as @elgehelge notes below.

Answered By: Joe Kington

Setting the bounding box when saving will also show the labels:

figure.savefig('myplot.png', bbox_inches='tight')
Answered By: Adam Greenhall
plt.tight_layout()

But be sure to add this command after plt.plot() or plt.bar()

Answered By: elgehelge
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.