【问题标题】:Histogram with custom y frequency python具有自定义y频率python的直方图
【发布时间】:2019-05-16 21:18:01
【问题描述】:

我正在尝试绘制以下数据

+-----------+------+------+
| Duration  | Code | Seq. |
+-----------+------+------+
|    116.15 |   65 |    1 |
|    120.45 |   65 |    1 |
|    118.92 |   65 |    1 |
|      7.02 |   66 |    1 |
|     73.93 |   66 |    2 |
|    117.53 |   66 |    1 |
|       4.4 |   66 |    2 |
|    111.03 |   66 |    1 |
|      4.35 |   66 |    1 |
+-----------+------+------+

我的代码如下:

x1 = df.loc[df.Code==65, 'Duration']
x2 = df.loc[df.Code==66, 'Duration']
kwargs = dict(alpha=0.5, bins=10)
plt.hist(x1, **kwargs, color='k', label='Code 65')
plt.hist(x2, **kwargs, color='g', label='Code 66')

我理想地想要在 y 轴上是 Seq.对应于 x 轴上不同的 Durations 的数量。但是现在,我只得到了Durationson y 的计数。我该如何纠正这个问题?

【问题讨论】:

  • 你的预期输出是什么
  • 你想要这个:df.groupby('Code').plot(y='Seq.', x='Duration', kind='bar', subplots=True)?你说hist 所以可能不是。你的预期输出是什么。
  • 我认为以上内容没有帮助。我希望看到直方图并计算 Seq 的数量。在每个持续时间(针对不同的代码)

标签: python pandas histogram


【解决方案1】:

您可以使用 pandas 对“x”值进行分类,然后改用条形图。

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Duration':[116.15, 120.45,118.92,7.02,73.93, 117.53, 4.4, 111.03, 4.35]})
df['Code'] = [65,65,65,66,66,66,66,66,66]
df['Seq.'] = [1,1,1,1,2,1,2,1,1]
df

   Duration  Code  Seq.
0    116.15    65     1
1    120.45    65     1
2    118.92    65     1
3      7.02    66     1
4     73.93    66     2
5    117.53    66     1
6      4.40    66     2
7    111.03    66     1
8      4.35    66     1

df['bin'] = pd.cut(df['Duration'],10, labels=False)
df

   Duration  Code  Seq.  bin
0    116.15    65     1    9
1    120.45    65     1    9
2    118.92    65     1    9
3      7.02    66     1    0
4     73.93    66     2    5
5    117.53    66     1    9
6      4.40    66     2    0
7    111.03    66     1    9
8      4.35    66     1    0
x1 = df.loc[df.Code==65, 'bin']
x2 = df.loc[df.Code==66, 'bin']
y1 = df.loc[df.Code==65, 'Seq.']
y2 = df.loc[df.Code==66, 'Seq.']

plt.bar(x1, y1)
plt.bar(x2, y2)
plt.show()

【讨论】:

  • 当我运行 df['bin'] 行时,它会在 bin 列中给出所有 nan。
  • 我已经更新了代码以显示整个输出,因此如果您的数据与您提供的数据不同,可能需要调整 cut 命令。此外,这种方法将每个 bin 中的 Seq 值相加。相反,如果您想知道有多少 Seq.值是 1 对 2,那么您可能需要不同的视觉原因,然后您要求三个维度(Seq. 计数 by duration(bin) + Seq.#)
猜你喜欢
  • 1970-01-01
  • 2017-05-04
  • 2017-04-23
  • 1970-01-01
  • 2015-10-11
  • 2020-05-10
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多