【问题标题】:Cummulative Frequency Distribution of a Histogram Bin(s) Inserts直方图箱的累积频率分布)插入
【发布时间】:2020-11-19 22:31:07
【问题描述】:

我想问是否有办法将插入的时间序列绘制到直方图箱。

输入是一个带有 x 和 y 值(整数)的大列表。我可以使用 plt.hist() 和多个 bin 轻松生成直方图,但我希望看到随着时间推移插入 bin 0(x 值)。

因此,在绘图中,我将有一个 x 轴显示时间,一个 y 轴显示计数,每个 bin 都有一条累积线。

谢谢

【问题讨论】:

  • 能否给我们一个数据示例(作为文本),也许还有一张你所追求的图?
  • 数据:x = [0,1,2.....,1048576], y = [1135534, 8348293423, 38944345(总共 1048576 个元素)]。我可以把 y 放在一个列表中,然后用各种箱子来绘制它。所以最后你有一个带有各种箱的简单直方图。我想随着时间的推移看到每个垃圾箱中的插入物。
  • 即使从 y 插入到 bin 中以 x 作为折线图上的 x 轴也可以。
  • 好的,我想我有一个视觉。本质上,X 是时间,Y 是累积值,每个 bin 都有一个轨迹。什么是 bin 宽度? ... 或者我将派生一个示例数据集进行演示。
  • bin 宽度可以是任意的。

标签: python pandas matplotlib histogram


【解决方案1】:

我不确定我对您的问题的理解是否正确,但我倾向于认为您希望随着时间的推移可视化在给定 bin 中插入的值,因为这些值是一一出现的。

In [1]: import numpy
   ...: import pandas
   ...: import matplotlib.pyplot as plt

# Let's first create the example data set...
In [2]: lowest, highest = 0, 10
   ...: amount_of_samples = 100
   ...: samples = numpy.random.randint(lowest, highest+1, amount_of_samples)

# ...then make 6 bins...
In [3]: amount_of_bins = 6
   ...: bins = [
   ...:     (i*highest/amount_of_bins, (i+1)*highest/amount_of_bins)
   ...:     for i in range(amount_of_bins)
   ...: ]

# ...and, finally, assign each value to the appropriate bin.
In [4]: df = pandas.DataFrame(
   ...:     data=[
   ...:         [1 if (sample >= interval[0] and sample < interval[1]) else 0
   ...:          for interval in bins]
   ...:         for sample in samples],
   ...:     columns=[f'{bins[i][0]:.1f}-{bins[i][1]:.1f}' for i in range(6)],
   ...: )

# We need to account for the fact that the above command excludes
# the highest value from the bins
In [5]: last_bin_column = f'{bins[-1][0]:.1f}-{bins[-1][1]:.1f}'
   ...: df[last_bin_column] += (samples == highest)

# We then get a cumulative sum for each bin, through time
In [6]: df = df.cumsum()

In [7]: ax = df.plot()

In [8]: ax.set_xlabel('time')
Out[8]: Text(0.5, 0, 'time')

In [9]: plt.savefig('hist.jpg', bbox_inches='tight')

【讨论】:

  • 是的,这就是我想要的解决方案。谢谢。
猜你喜欢
  • 2022-01-15
  • 2016-04-30
  • 2020-03-28
  • 1970-01-01
  • 2014-05-30
  • 2021-06-02
  • 1970-01-01
  • 2017-12-23
  • 2012-10-16
相关资源
最近更新 更多