python - 具有自定义 y 频率的直方图 python

标签 python pandas histogram

我正在尝试绘制以下数据

+-----------+------+------+
| 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。但现在,我只能得到 y 上的Durations计数。我该如何纠正这个问题?

最佳答案

您可以使用 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()

关于python - 具有自定义 y 频率的直方图 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56176748/

相关文章:

python - 带有 PK 的 Django REST POST 到 HyperlinkedModelSerializer,如何将 PK 转换为 URL?

python - 捕获所有 * 前面没有 < 的组

python - 数据框中的替换功能删除的内容超出预期

python - 将具有重复索引的系列数据附加到 pandas 数据框列

r - 带计数 R 的直方图

python - 索引错误: index 1 is out of bounds for axis 0 with size 1 while storing the result as a tuple in python

python - 使用 Xcode 3.2 进行 PyObjC 开发

python - Pandas/Python 如何在保留 df 结构的同时切换数据框中的索引/列?

python - 使用欧氏距离计算 2 个直方图之间的距离

python - 骰子实验结果的分布