【问题标题】:Python matplotlib how to change y-values of "histogram"Python matplotlib如何更改“直方图”的y值
【发布时间】:2020-09-02 01:23:37
【问题描述】:

我正在尝试创建“直方图”,但 y 轴不应该是 bin 内数据点的频率。相反,我希望为每个 bin 设置我自己的 y 轴值。

例如,假设我的x 值为:[1, 2.2, 1.4, 2, 3.3, 2.6, 3, 1.5, 3.9] and my y-values are [1, 2, 2.5, 1, 0.5, 3, 4, 3, 2]

将此视为一个函数:每个x 值对应于y 值(即x 数组的第一个索引中的值映射到y 的第一个索引中的值数组,第二个索引到第二个等)。

我希望对 x 值进行分箱,并绘制与每个箱的 x 值相对应的 y 值的总和。

例如,假设我要创建 3 个垃圾箱。第一个 bin 将包含 x1, 1.4, 1.5, 并且为该 bin 绘制的是相应 y 值的总和(因此 1 + 2.5 + 3 = 6.5)。

我怎样才能做到这一点?

编辑:我想一个更简单的问题是:如何创建一个以数字为 x 轴并带有连续条形的条形图(即条形之间没有间隙)

【问题讨论】:

  • 我在绘图条上添加代码,这是你需要的吗?

标签: python numpy matplotlib


【解决方案1】:

我使用了你的示例数据,这里是代码

import numpy as np

x = np.array([1, 2.2, 1.4, 2, 3.3, 2.6, 3, 1.5, 3.9])
# sort x and y
ind = np.argsort(x)
x1 = x[ind]
y = np.array([1, 2, 2.5, 1, 0.5, 3, 4, 3, 2])
y1 = y[ind]

# count bins
y2, t = np.histogram(x1, bins=3)
ind1 = y2.cumsum()
ind2 = np.array([0]+[e for e in ind1[0:-1]])

# sum based on counts
y_final = [y1[i:j].sum() for (i, j) in zip(ind2, ind1)]

# plot bar, specify the width
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.bar(t[0:3], y_final, width=np.diff(t)[0])

【讨论】:

    【解决方案2】:

    您似乎在描述plt.histweights= 参数:

    import matplotlib.pyplot as plt
    
    x = [1, 2.2, 1.4, 2, 3.3, 2.6, 3, 1.5, 3.9]
    y = [1, 2, 2.5, 1, 0.5, 3, 4, 3, 2]
    plt.hist(x, weights=y, bins=3)
    

    左边是默认直方图,中间是histtype='step',更类似于函数的绘制方式。右侧的子图添加了一个stemplot,显示了 x 和相应的 y 值。

    【讨论】:

    • 这比我的回答好多了:) 谢谢!,我也学到了很多。
    猜你喜欢
    • 2020-12-26
    • 2017-05-04
    • 2017-11-17
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2014-04-15
    • 2020-05-20
    相关资源
    最近更新 更多