Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python + matplotlib: barh plot show incomplete YTick labels - how to dynamically move the plot area to the right to fit the given YTickLabels?

I'm using matplotlib to plot a barh plot to a file. Unfortunate, the YTickLaels are a bit too long and the plot area won't move to the right automatically. Is there a way to move the plot area to the right automatically so I won't have problems with incomplete YTickLabels?

The code I use is the following:

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2 is longer than others': 17, u'Label3 is not so short either':30}
fig = plt.figure(figsize=(5.5,3),dpi=300)
ax = fig.add_subplot(111)
ax.grid(True,which='both')
bar = ax.barh(range(1,len(D)+1,1),D.values(),0.4,align='center')
plt.yticks(range(1,len(D)+1,1), D.keys(), size='small')
fig.savefig('D_bar.png')

Here is the output: output of barh

How can I fix this? Thanks

like image 458
otmezger Avatar asked Apr 15 '13 09:04

otmezger


People also ask

How do I move the Xticks in Python?

If you know the tick positions, you can do something like for pos, tick in zip(ticks, ax. xaxis. get_majorticklabels()): tick. set_x(pos - 0.1) tick.

How do I move the legend box in matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.


1 Answers

Actually, there is an automatic way of doing this now: tight_layout.

In your case:

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2 is longer than others': 17, 
     u'Label3 is not so short either':30}
fig = plt.figure(figsize=(5.5,3),dpi=300)
ax = fig.add_subplot(111)
ax.grid(True,which='both')
bar = ax.barh(range(1,len(D)+1,1),D.values(),0.4,align='center')
plt.yticks(range(1,len(D)+1,1), D.keys(), size='small')
fig.tight_layout() # <---- ADD THIS
fig.savefig('D_bar.png')
like image 51
Joe Kington Avatar answered Sep 20 '22 22:09

Joe Kington