Skip to main content
 首页 » 编程设计

python之Python 中带有额外线条的 Matplotlib 累积频率图

2025年04月02日24虾米哥

当我运行我的代码来生成数据集的相对累积频率的图表时,我的图表在图表与 y=1 线相交的点处直线向下右侧,like this one .

y 轴限制在 y=0 到 y=1 的范围内,代表累积频率的 0% 到 100%,一旦图形达到 y=1,或 100%,它应该继续 y=1 直到 x 轴的上限,从 x=0 到 x=2,类似于 this graph .

有什么方法可以确保直方图在达到 y=1 后在 y=1 处继续?我需要我的 x 轴保持在 [0,2] 范围内,y 轴保持在 [0,1] 范围内。

这是我用来生成图表的 Python 代码:

import matplotlib.pyplot as plt  
# ... 
plt.ylabel('Relative Cumulative Frequency') 
plt.xlabel('Normalized Eigenvalues') 
plt.hist(e.real, bins = 50, normed=1, histtype='step', cumulative=True) 
# Limit X and Y ranges    
plt.xlim(0, 2) 
plt.ylim(0, 1) 

谢谢,麦克斯

请您参考如下方法:

您可以通过创建自己的垃圾箱和 setting the last bin to np.Inf 来做到这一点:

import matplotlib.pyplot as plt 
import numpy as np 
... 
x = np.random.rand(100,1) 
 
plt.ylabel('Relative Cumulative Frequency') 
plt.xlabel('Normalized Eigenvalues') 
 
binsCnt = 50 
bins = np.append(np.linspace(x.min(), x.max(), binsCnt), [np.inf]) 
plt.hist(x, bins = bins, normed=1, histtype='step', cumulative=True) 
# Limit X and Y ranges 
plt.xlim(0, 2) 
plt.ylim(0, 1) 
plt.show()