Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rotating xticks causes the ticks partially hidden in matplotlib

Tags:

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..?

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")
like image 767
markjason72 Avatar asked Jul 15 '11 10:07

markjason72


People also ask

How do I rotate axis ticks in MatPlotLib?

Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax.

What does Xticks do in MatPlotLib?

pyplot. xticks. Get or set the current tick locations and labels of the x-axis.

How do I control the number of Xticks in MatPlotLib?

locator_params() to change the number of ticks on an axis. Call matplotlib. pyplot. locator_params(axis=an_axis, nbins=num_ticks) with either "x" or "y" for an_axis to set the number of ticks to num_ticks .

How do I get rid of Xticks in MatPlotLib?

Matplotlib removes both labels and ticks by using xticks([]) and yticks([]) By using the method xticks() and yticks() you can disable the ticks and tick labels from both the x-axis and y-axis. In the above example, we use plt.


2 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.

like image 149
Joe Kington Avatar answered Oct 08 '22 16:10

Joe Kington


plt.tight_layout()

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

like image 37
elgehelge Avatar answered Oct 08 '22 18:10

elgehelge