2Obe
2Obe

Reputation: 3720

Matplotlib y axis scale not fitting values

I plot the probability mass function of a binomial distribution with:

fig=plt.figure(figsize=(10,10))
binom=[scs.binom.pmf(k,100,0.2) for k in range(100)]
print(np.max(binom)) #0.0993002148088
[plt.axvline(k,ymax=scs.binom.pmf(k,100,0.2)) for k in range(100)]
plt.ylim(ymax=0.1)

plt.show()

As you see the maximum value of binom is 0.099300 means the plot should nearly reach the upper limit of the y-axis but the result is as follows:

enter image description here

So what am I doing wrong? Why is the graph not fitting to the limits?

Upvotes: 0

Views: 1238

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339775

I think you may want to use a stem plot.

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as scs

fig=plt.figure(figsize=(10,10))
binom=[scs.binom.pmf(k,100,0.2) for k in range(100)]

# Scale the yvalues by ymax
plt.stem(binom, linefmt='b-', markerfmt='none', basefmt='none')

plt.show()

enter image description here

Upvotes: 2

tmdavison
tmdavison

Reputation: 69228

The problem is that axvline accepts values in the range 0 to 1 for ymax (i.e. it is in axes coordinates, not data coordinates). From the docs:

ymax : scalar, optional, default: 1

Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

So, you are telling it to only plot around 0.1 of the way up the axes. If you wish to stick with using axvline to make the plot, you will need to scale the values before you plot them.

e.g.

fig=plt.figure(figsize=(10,10))
binom=[scs.binom.pmf(k,100,0.2) for k in range(100)]
print(np.max(binom)) #0.0993002148088
# Set ymax here
ymax = 0.1
# Scale the yvalues by ymax
[plt.axvline(k,ymax=scs.binom.pmf(k,100,0.2)/ymax) for k in range(100)]
# Use ymax again here
plt.ylim(ymax=ymax)

plt.show()

Alternatively, you might want to look into using plt.bar to make this plot; for example:

plt.bar(range(len(binom)), binom)

Upvotes: 1

Related Questions