psoares
psoares

Reputation: 4883

blank space in the top of the plot matplotlib django

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)

Upvotes: 2

Views: 3224

Answers (1)

Joe Kington
Joe Kington

Reputation: 284752

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

Another very useful method is plt.margins(...)/ax.margins(). It will act similar to axis('tight'), but will leave a bit of padding around the limits.

As an example of your problem:

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()

Auto-rounded y-axis limits

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

Tight axis limits

However, you might not want things to be too tight, so you could use plt.margins(0.02) to add 2% padding in all directions. You can then set the left-hand limit back to 0 with plt.xlim(xmin=0):

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)

plt.margins(0.05)
plt.xlim(xmin=0)

plt.show()

Which produces a bit nicer of a plot:

Nicely padded margins

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

Upvotes: 7

Related Questions