python - 如何使用 matplotlib 创建多个饼图

标签 python pandas matplotlib data-visualization pie-chart

我有一个 Pandas DataFrame 看起来像这样

Year    EventCode   CityName    EventCount
2015    10          Jakarta     12
2015    10          Yogjakarta  15
2015    10          Padang      27
...
2015    13          Jayapura    34 
2015    14          Jakarta     24
2015    14          Yogjaarta   15
...
2019    14          Jayapura    12  

我想可视化具有最大 EventCount 的前 5 个城市(带饼图),每年按事件代码分组

我该怎么做?

最佳答案

这可以通过使用 pivot_table 重组您的数据来实现, 使用 sort_values 过滤热门城市和 DataFrame.plot.pie带有 subplots 参数的方法:

# Pivot your data
df_piv = df.pivot_table(index='EventCode', columns='CityName',
                        values='EventCount', aggfunc='sum', fill_value=0)


# Get top 5 cities by total EventCount
plot_cities = df_piv.sum().sort_values(ascending=False).head(5).index

# Plot
df_piv.reindex(columns=plot_cities).plot.pie(subplots=True,
                                             figsize=(10, 7),
                                             layout=(-1, 3))

[输出]

enter image description here

关于python - 如何使用 matplotlib 创建多个饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60601059/

相关文章:

python - 在 Python 中将图例标签设置为日期

c++ - 处理多个登录系统

python - 在 pandas 数据框列上使用 rsplit 根据分隔符的第二个实例进行分隔

python - 使用 Pandas 从文本文件中提取标题数据

python - Seaborn Jointplot 更改 Figsize

python - 使用 matplotlib 的动态图在一段时间后变慢

python - 有没有办法在类定义之后设置元类?

python - 从日期时间 Pandas 中提取季节

python - 通过 socket.sendto() 发送附加参数

python - 使用关联列表对象的函数迭代列表