python - Matplotlib:在给定预先计算的计数和 bin 的情况下绘制直方图
问题描述
我有一些数据x
传递给以numpy.histogram(x)
获取计数和 bin 边缘。然后我将这些保存到文件中。稍后,我想加载这些数据并绘制直方图。
我有
counts = [20, 19, 40, 46, 58, 42, 23, 10, 8, 2]
bin_edges = [0.5, 0.55, 0.59, 0.63, 0.67, 0.72, 0.76, 0.8, 0.84, 0.89, 0.93]
如何绘制此直方图?
解决方案
Pyplotbar
可以在边缘对齐使用(默认居中),宽度计算如下np.diff
:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
counts = np.array([20, 19, 40, 46, 58, 42, 23, 10, 8, 2])
bin_edges = np.array([0.5, 0.55, 0.59, 0.63, 0.67, 0.72, 0.76, 0.8, 0.84, 0.89, 0.93])
ax.bar(x=bin_edges[:-1], height=counts, width=np.diff(bin_edges), align='edge', fc='skyblue', ec='black')
plt.show()
可以选择将 xticks 设置为 bin 边缘:
ax.set_xticks(bin_edges)
或到垃圾箱中心:
ax.set_xticks((bin_edges[:-1] + bin_edges[1:]) / 2)
推荐阅读
- javascript - 如何使用数据表添加自定义标题并制作全宽 PDF
- javascript - 输入值jQuery检查长度和值?
- sql-server - 有没有办法在 Azure SQL 中使用 CLR 程序集?
- powershell - 计算自上次使用 PowerShell 安装程序以来的天数
- bash - make 函数如何在 makefile 中运行的 Bash 循环中工作
- algorithm - 黑白滑块滤镜控制
- java - 解析JSONObject时如何制作容错代码?
- random - 在 ABAP CDS 视图中创建随机字符串
- python-3.x - 字典列表
- qt - 鼠标点击事件上的QtQuick pathCurve曲线