python - 是否可以使用 Get 和 Set 操作 matplotlib 直方图中的数据?
问题描述
我有一个使用 matplotlib 制作的堆叠直方图。它当然有多个箱(在每个扇区上),并且每个箱/条进一步细分为子扇区(堆叠直方图)。
我想知道如何获取数据点,做一些数学运算(假设将每个 bin 除以它的总值),然后设置新的数据点。
我希望它如何工作:
import matplotlib.plt as plt
ax = plt.subplt(111)
h = ax.hist((subsector1,subsector2,subsector3), bins = 20, stacked=True)
y_data = h.get_yData
y_data 的形状类似于 20 x 3 (bins x subsectors)
new_y_data = y_data normalized by total on each bin
new_y_data 的形状也类似于 20 x 3,但每个 bin 的总和为 1(或 100%)
new_h = h.set_yData(new_y_data)
new_h 看起来更像一个条形图,具有相同大小的条形,但每个条形上的子部门分布不同..
这在 python matplotlib 中甚至可能吗?
解决方案
当您只需要这些值时,更容易使用np.histogram
无需绘制即可进行相同计算的方法。
当你有值时,plt.bar
直接绘制而不需要plt.hist
.
熊猫plot.bar
可能是另一种选择。查看使用 groupby 创建百分比堆积条形图,以获取与您类似的示例。
np.histogram
这是一些使用and的示例代码plt.bar
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
subsector1 = np.clip(np.random.normal(70, 20, 400), 0, 100)
subsector2 = np.clip(np.random.normal(50, 20, 1000), 0, 100)
subsector3 = np.clip(np.random.normal(25, 20, 500), 0, 100)
num_bins = 20
x_min = np.min(np.concatenate([subsector1, subsector2, subsector3]))
x_max = np.max(np.concatenate([subsector1, subsector2, subsector3]))
bounds = np.linspace(x_min, x_max, num_bins + 1)
values = np.zeros((num_bins, 3))
for i, subsect in enumerate((subsector1, subsector2, subsector3)):
values[:, i], _ = np.histogram(subsect, bins=bounds)
with np.errstate(divide='ignore', invalid='ignore'):
values /= values.sum(axis=1, keepdims=True)
fig, ax = plt.subplots()
bottom = 0
for i in range(3):
plt.bar((bounds[:-1] + bounds[1:]) / 2, values[:, i], bottom=bottom, width=np.diff(bounds) * 0.8)
bottom += values[:, i]
plt.xlim(x_min, x_max)
plt.gca().yaxis.set_major_formatter(PercentFormatter(1.0))
plt.show()
推荐阅读
- c# - 错误 CS7069 对类型“图像”的引用声称它是在“System.Drawing”中定义的,但找不到它
- postgresql - CentOS8 上安装 PostgreSQL12.4 警告:/etc/ld.so.conf.d/postgresql-pgdg-libs.conf: No such file or directory
- babeljs - 添加 @babel/helper-annotate-as-pure 后,Babel 给 Plugin/Preset 没有返回对象
- javascript - php,Laravel 7 - 无法从 AJAX 请求接收数据
- gradle - 杰克逊数据绑定问题 - Gradle
- unity3d - Unity Player 向下漂浮而不是掉落
- javascript - 将过滤器发送到 react-admin 列表中的导出器
- python - 如何根据 django 中的帖子标题生成 slug?
- linux - 使用 awk 和 truncate 写入同一个文件
- r - 使用 R6 高效创建对象