首页 > 解决方案 > 是否可以使用 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 中甚至可能吗?

标签: pythonmatplotlibhistogrammatlab-figure

解决方案


当您只需要这些值时,更容易使用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()

示例图


推荐阅读