首页 > 解决方案 > 有没有办法从python中的直方图中保存垃圾箱?

问题描述

我最近开始学习 Python 课程,我们需要绘制直方图,然后检索生成的 bin。代码如下:

fig, axs = plt.subplots(1, 1,
                        figsize =(10, 5), 
                        tight_layout = True)
axs.hist(diferencia[14329:27006], bins=10, rwidth = 0.8)
plt.show()
print("\n")
plt.savefig("histograma.png")

直方图生成得很好,但我无法从中获取垃圾箱。抱歉这个基本问题,我只是 python 的初学者。谢谢!

标签: pythonmatplotlibhistogram

解决方案


您可以保存histvia的信息values, bins, patches = ax.hist(...)bins将是 bin 边界数组(比条数多一个)。

这是一个示例用法,可以进一步阐明这个想法。bin 边界都用于文本输出,以显示每个 bin 的背景。请注意,选择rwidth与 1 不同的值可能会给人一种错误印象,即介于两者之间的某些值不是数据集的一部分。另一种方法是应用边缘颜色。

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle

fig, axs = plt.subplots(figsize=(10, 5))
N = 2000
values, bins, patches = axs.hist(np.random.randn(N), bins=10, rwidth=0.8, color='dodgerblue', edgecolor='white')
for val, b0, b1, color in zip(values, bins[:-1], bins[1:], cycle(['crimson', 'lightblue'])):
    print(f'Bin {b0:.3f},{b1:.3f}: {val:.0f} entries ({val / N * 100:.2f} %)')
    axs.axvspan(b0, b1, color=color, alpha=0.1, zorder=0)
axs.margins(x=0)
plt.show()

样本直方图

Bin -3.132,-2.483: 11 entries (0.55 %)
Bin -2.483,-1.833: 52 entries (2.60 %)
Bin -1.833,-1.184: 162 entries (8.10 %)
Bin -1.184,-0.534: 354 entries (17.70 %)
Bin -0.534,0.116: 493 entries (24.65 %)
Bin 0.116,0.765: 486 entries (24.30 %)
Bin 0.765,1.415: 284 entries (14.20 %)
Bin 1.415,2.064: 117 entries (5.85 %)
Bin 2.064,2.714: 35 entries (1.75 %)
Bin 2.714,3.364: 6 entries (0.30 %)

如果您需要更好看的垃圾箱数字,您可以在ax.hist(..., bins=...). 默认使用bins=np.linspace(min_value, max_value, 11). 一个例子可能是bins=np.arange(-4, 4.1, 0.5)

PS:请注意,最好先调用savefigplt.show()因为后者在关闭时恰好会擦除情节。


推荐阅读