Reputation: 2297
I am using matplotlib
to plot a histogram where each bin contains 1 value. Here's a sample:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def image():
# Generate a bunch of random data, here's an example
TYPE1 = [128, 129, 132, 6, 136, 139, 12, 13, 142, 140]
TYPE2 = [18, 147, 148, 23, 152, 26, 154, 156, 157, 158]
TYPE3 = [159, 161, 165, 42, 44, 172, 176, 182, 188, 62]
TYPE4 = [190, 193, 198, 199, 72, 77, 80, 82, 215, 216]
TYPE5 = [218, 223, 95, 226, 101, 106, 108, 109, 113, 127]
fig, ax = plt.subplots(1, 1)
ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.hist([TYPE1, TYPE2, TYPE3, TYPE4, TYPE5],
color=['white', 'white', '0.8', 'green', 'black'],
label=['TYPE1', 'TYPE2', 'TYPE3', 'TYPE4', 'TYPE5'],
stacked=True,
bins=250)
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True)
plt.tight_layout()
plt.show()
How do I reduce the spacing on the y axis between 0
and 1
to be say a quarter of the actual height to make it look like something as follows with a reduced height of the axis?
Upvotes: 0
Views: 176
Reputation: 39072
You can define the figure size where you can use a smaller height. Moreover, you do not need to define the ax
again. I have commented out the redundant line. I would also use a 2 column format for the legends using the keyword ncol=2
. It looks better.
fig, ax = plt.subplots(1, 1, figsize=(6, 2.5))
# ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True, ncol=2)
Upvotes: 1