Matplotlib y轴比例不适合值

2024-05-23 17:39:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我用以下公式绘制二项分布的概率质量函数:

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

如您所见,binom的最大值为0.099300,表示绘图应接近y轴的上限,但结果如下:

enter image description here

我做错什么了?为什么图形不符合极限?在


Tags: 函数infor质量fig绘制rangeplt
2条回答

问题是^{}接受ymax范围0到1的值(即,它在轴坐标系中,而不是在数据坐标系中)。从文件中:

ymax : scalar, optional, default: 1

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

所以,你告诉它只在轴上0.1处绘制。如果您希望继续使用axvline来绘制,则需要在绘制之前缩放这些值。在

例如

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

或者,您可以考虑使用plt.bar来绘制此图;例如:

^{pr2}$

我想你可以用^{} 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

相关问题 更多 >