【问题标题】:How can i create multiple pie chart using matplotlib如何使用 matplotlib 创建多个饼图
【发布时间】:2023-03-14 11:01:03
【问题描述】:

我有一个 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 个城市(带有饼图),按事件代码分组

我该怎么做?

【问题讨论】:

  • 我可以自动迭代一个函数以将其可视化,而无需在subplot 中手动绘制它吗?
  • 如果要绘制5个图表,可以使用for i in range(1, 6): plot.subplot(f'51{i}')

标签: python pandas matplotlib data-visualization pie-chart


【解决方案1】:

这可以通过使用pivot_table 重构您的数据、使用sort_values 过滤顶级城市和使用subplots 参数的DataFrame.plot.pie 方法来实现:

# 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))

[出]

【讨论】:

    【解决方案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))
    )
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多