使用pandas plot生成年龄预定义桶的直方图

2024-06-02 07:46:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张表格

+-------+-----+
| Name  | Age |
+-------+-----+
| John  |  45 |
| Tim   |  29 |
| Elisa |  28 |
| Sarah |  32 |
+-------+-----+

我想使用df.plot.hist功能来创建直方图,但我想按预定的年龄段(如18-30、31-45、46-65等)排序,而不是使用df['Age'].plot.hist(bins=20)自动设置要使用的存储段

此外,我还想使用百分比分布而不是频率分布。我试图传递norm=True,但仍然需要帮助将其转换为百分比

有办法吗


Tags: name功能dfage排序plot直方图john
1条回答
网友
1楼 · 发布于 2024-06-02 07:46:04

你太近了!从matplotlib hist(熊猫正在使用的)的docString中,您有“bin:int或sequence或str”

因此,您可以传递一个数字列表,定义拆分的位置

import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot') # makes plot looks much nicer

col_names = ['Name', 'Age']
d = dict(
    Elisa = 28,
    Tim   = 29,
    Sarah = 32,
    John  = 45
)

custom_bins = [18, 31, 42, 66]

df = pd.DataFrame(d.items(), columns=col_names)
df.plot.hist('Age', bins=custom_bins)
plt.show()

enter image description here

相关问题 更多 >