rotating xticks causes the ticks partially hidden in matplotlib
I am creating a plot 开发者_JS百科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.
Is there some way I can make the whole plot accommodate everything..?thanks
mark
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")
plt.tight_layout()
But be sure to add this command after plt.plot()
or plt.bar()
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.
Setting the bounding box when saving will also show the labels:
figure.savefig('myplot.png', bbox_inches='tight')
精彩评论