python - 具有自定义y频率python的直方图
问题描述
我正在尝试绘制以下数据
+-----------+------+------+
| 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 轴上想要的是 .对应于 x 轴上Seq
不同的数量。Durations
但是现在,我只得到了Durations
y 的计数。我该如何纠正?
解决方案
您可以使用 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()
推荐阅读
- r - 如何在 R 中使用多列作为应用函数的输入
- java - Spring Boot:Slice/Pageable 未根据页面返回正确的块
- java - Java webclient 在字符串响应中返回 2 个双引号
- ios - 替换 iOS 15 中已弃用的 `SecTrustGetCertificateAtIndex`?
- firebase - 在 firebase 中添加所有数字并将其存储在 Flutter 中的变量中
- java - Failsafe : 执行 void 方法并根据成功/失败返回结果
- datetime - 发布时,报告日期/时间与桌面相比有所不同
- angular - 升级到 Angular 12 后反映元数据错误
- javascript - 使用来自 javascript 函数的 jsx 代码在根目录中编写一个 jsx 文件
- javascript - 如何在 Next.js 中设置没有 {styles.red} 的 className