I have a Python program that generates a histogram using matplotlib. The problem is that the images that are generated sometimes get cropped at the top. First, here's the relevant code excerpt, where plt
is matplotlib.pyplot
and fig
is matplotlib.figure
:
plt.hist(grades, bins=min(20, maxScore), range=(0,maxScore), figure=fig.Figure(figsize=(3,2), dpi=150))
plt.xlabel("Raw Score")
plt.ylabel("Count")
plt.title("Raw Score Histogram")
plt.savefig(histogramFile)
The problem appears in a situation like the following. I might have 300 elements in grades
, 3 of the bins have more than 20 elements in them, and the rest less than 20. The ones with more than 20 will have their tops cut off and the y-axis will only go up to 20. This doesn't always happen though: a different 300 elements in grades
with a similar distribution might render correctly, with the y-axis scaling to fit within the figsize
. Also note that the x-axis always comes out right.
What can I do to get the y-axis to scale correctly and produce bars that fit within the image?