views:

89

answers:

1

Hi again people :)

I've a question about matplotlib bars. I've already made some bar charts but I don't know why, this one left a huge blank space in the top.

the code is similar to other graphics I've made and they don't have this problem.

If anyone has any idea, I appreciate the help.

x = matplotlib.numpy.arange(0, max(total))
ind = matplotlib.numpy.arange(len(age_list))

ax.barh(ind, total)

ax.set_yticks(ind) 
ax.set_yticklabels(age_list)
+1  A: 

By "blank space in the top" do you mean that the y-limits are set too large?

By default, matplotlib will choose the x and y axis limits so that they're rounded to the closest "even" number (e.g. 1, 2, 12, 5, 50, -0.5 etc...).

If you want the axis limits to be set so that they're "tight" around the plot (i.e. the min and max of the data) use ax.axis('tight') (or equivalently, plt.axis('tight') which will use the current axis).

For example, if I do something like this:

import numpy as np
import matplotlib.pyplot as plt

# Make some data...
age_list = range(10,31)
total = np.random.random(len(age_list))
ind = np.arange(len(age_list))

plt.barh(ind, total)

# Set the y-ticks centered on each bar
#  The default height (thickness) of each bar is 0.8
#  Therefore, adding 0.4 to the tick positions will 
#  center the ticks on the bars...
plt.yticks(ind + 0.4, age_list)

plt.show()

I get this:Auto-rounded y-axis limits

If I wanted the limits to be tighter, I could just call plt.axis('tight') after the call to plt.barh, which would give this: Tight axis limits

However, you might not want things to be too tight, so you might do something like this:

import numpy as np
import matplotlib.pyplot as plt

# Make some data...
age_list = range(10,31)
total = np.random.random(len(age_list))
ind = np.arange(len(age_list))

height = 0.8
plt.barh(ind, total, height=height)

plt.yticks(ind + height / 2.0, age_list)

# Set the axis limits to be a bit more reasonable
# Pad the axis limits by "padding" (which, in this case,
# is the amount of space between each bar when the "height"
# is set to 0.8
padding = 0.2
plt.ylim([ind.min() - padding, ind.max() + height + padding])

plt.show()

Which produces a bit nicer of a plot: Nicely padded y-axis

Hopefully that points you in the right direction, at any rate!

Joe Kington
+1 Detailed with clear explanations _and_ screenshots.
Manoj Govindan
Thanks a lot!I had a graphic like the first one you draw, after making the changes I was able to see one similar with yours!You explained very well and it make sense :)
Pat