【问题标题】:How do I rearrange the order of pie slices in pandas plot?如何在熊猫图中重新排列饼图的顺序?
【发布时间】:2022-01-16 20:27:30
【问题描述】:

我正在尝试重新排列饼图中饼图的顺序。我对 Python 比较陌生,无法弄清楚这一点。这是我当前的代码:

df.groupby(['Country']).sum().plot(kind='pie', y='Alcohol_Consumption', subplots=True, shadow = True,startangle=-270,
figsize=(15,10), autopct='%1.1f%%', counterclock=False,)

plt.show()

饼图切片按国家/地区名称的字母顺序排列,即使我的数据框不同。那么,如何将饼图切片的顺序更改为与数据框相同?

这是生成的饼图:

数据框:https://cdn.discordapp.com/attachments/925138838588911626/932369853220810833/unknown.png

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    如果每个国家/地区仅在您的数据框中出现一次,您可以尝试df.set_index('Country').plot(kind='pie', y='Alcohol_Consumption')。如果每个国家/地区出现多​​次,您可以使用df['Country'] = pd.Categorical(df['Country'], df['Country'].unique()) 将现有排序强制为该列上的固定排序。

    这是一个简化的例子:

    import matplotlib.pyplot as plt
    import pandas as pd
    
    fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(14, 4))
    df = pd.DataFrame({'Country': ['c', 'b', 'a'],
                       'Consumption': [1, 2, 3]})
    df.groupby('Country').sum().plot(kind='pie', y='Consumption', ax=ax1)
    ax1.set_title('Just using groupby')
    
    df.set_index('Country').plot(kind='pie', y='Consumption', ax=ax2)
    ax2.set_title('Using set_index()\nsupposes Country is unique')
    
    df['Country'] = pd.Categorical(df['Country'], df['Country'].unique())
    df.groupby('Country').sum().plot(kind='pie', y='Consumption', ax=ax3)
    ax3.set_title('Using groupby, order\nforced via pd.Categorical')
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多