Skip to main content
 首页 » 编程设计

python之绘制直方图

2025年04月02日9hnrainll

我正在尝试用 mu 和 sigma 绘制直方图。

我试图在 y 轴上使用 ec_scores 值,它应该显示 0.1 到 1.0 它在 y 轴上给了我 1、2、3、4、5、6。 我没有收到任何错误,但这完全偏离了图表。请帮助我并告诉我我做错了什么以及如何正确生成图表。 谢谢。

这是我的代码:

import numpy as np 
 
import matplotlib.pyplot as plt 
 
import matplotlib.mlab as mlab 
 
x = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) 
 
ec_scores = np.array([1., 1., 1., 0.95923677, 0.94796184, 1., 0.76669558, 1., 0.99913194, 1.]) 
 
mu, sigma = (np.mean(ec_scores), np.std(ec_scores)) 
 
 
fig = plt.figure() 
 
ax = fig.add_subplot(111) 
 
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='blue', alpha=0.75) 
 
 
bincenters = 0.5*(bins[1:]+bins[:-1]) 
 
y = mlab.normpdf( bincenters, mu, sigma) 
 
l = ax.plot(bincenters, y, 'r--', linewidth=1) 
 
ax.set_xlabel('Parameters') 
 
ax.set_ylabel('EC scores ') 
 
plt.plot(x, ec_scores) 
 
ax.grid(True) 
 
plt.show() 

目前图表看起来像这样:

请您参考如下方法:

正如@benton 在评论中提到的,您可以将 ec_scores 绘制为 barchart :

import numpy as np 
import matplotlib.pyplot as plt 
 
x = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) 
ec_scores = np.array([1., 1., 1., 0.95923677, 0.94796184, 1., 0.76669558, 1., 0.99913194, 1.]) 
mu, sigma = (np.mean(ec_scores), np.std(ec_scores)) 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
rects = ax.bar(x, ec_scores, width=0.1, align='center', facecolor='blue', alpha=0.75) 
 
ax.set_xlabel('Parameters') 
ax.set_ylabel('EC scores ') 
ax.grid(True) 
 
plt.show() 

看起来像这样:

您还可以通过将数组传递给 yerr 参数来添加错误栏。这在我上面链接的条形图示例中有所说明。我不确定你到底想用 normpdf 做什么,但条形图返回一个矩形列表而不是垃圾箱,所以你可能需要根据你的代码进行调整。

希望对您有所帮助。