如何使用matplotlib创建多个饼图

2024-05-19 01:17:03 发布

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

我有一个熊猫数据框看起来像这样

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  

我想想象一下每年事件数最多的前5个城市(用饼图),按事件代码分组

我该怎么做


Tags: 数据代码事件year想象jakartacitynameeventcount
2条回答

Pandas支持自动将每个列打印到子图中。因此,您希望选择CityName作为索引,将EventCode作为列和绘图

(df.sort_values('EventCount', ascending=False) # sort descending by `EventCount`  
   .groupby('EventCode', as_index=False)
   .head(5)                                    # get 5 most count within `EventCode`
   .pivot(index='CityName',                    # pivot for plot.pie
          columns='EventCode',
          values='EventCount'
         )
   .plot.pie(subplots=True,                    # plot with some options
             figsize=(10,6), 
             layout=(2,3))
)

输出:

enter image description here

这可以通过使用^{}重新构造数据、使用^{}筛选顶级城市以及使用^{cd4>}参数的^{}方法来实现:

# 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

相关问题 更多 >

    热门问题