简体   繁体   English

Python matplotlib 如何更改“直方图”的 y 值

[英]Python matplotlib how to change y-values of "histogram"

I am trying to create a "histogram", except the y-axis is not supposed to be the frequency of data points within a bin.我正在尝试创建一个“直方图”,除了 y 轴不应该是 bin 内数据点的频率。 Instead, I wish to set my own y-axis values for each bin.相反,我希望为每个 bin 设置我自己的 y 轴值。

For example, let's say my x values are: [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值为: [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]

Treat this as a function: each of the x values corresponds to the y -values (ie, the value in the 1st index of x array maps to the value in the 1st index of y array, 2nd index to 2nd, etc.).将其视为 function:每个x值对应于y值(即, x数组的第一个索引中的值映射到y数组的第一个索引中的值,第二个索引映射到第二个索引,等等)。

I wish to bin the x values and plot the sum of the y values corresponding to the x values of each bin.我希望将x值和 plot 对应于每个 bin 的 x 值的y值的总和。

For example, let's say I were to create 3 bins.例如,假设我要创建 3 个垃圾箱。 The first bin would contain the x values 1, 1.4, 1.5, and what gets plotted for this bin is the sum of the corresponding y values (so 1 + 2.5 + 3 = 6.5 ).第一个 bin 将包含x1, 1.4, 1.5, ,为此 bin 绘制的是相应 y 值的总和(因此1 + 2.5 + 3 = 6.5 )。

How can I achieve this?我怎样才能做到这一点?

Edit: I guess a simpler question is: how do I create a bar graph with numerical numbers as the x-axis and with continuous bars (ie no gap between bars)编辑:我想一个更简单的问题是:如何创建一个以数字作为 x 轴并具有连续条形图(即条形之间没有间隙)的条形图

I used your example data, and here is the code我使用了您的示例数据,这是代码

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])

You seem to be describing the weights= argument of plt.hist :您似乎在描述weights=plt.hist参数:

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)

At the left the default histogram and at the center with histtype='step' which more resembles how a function would be plotted.左侧是默认直方图,中间是histtype='step' ,这更类似于 function 的绘制方式。 The subplot at the right adds a stem plot showing the x and corresponding y values.右侧的子图添加了一个stem plot ,显示了 x 和相应的 y 值。

示例图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM