如何重新排列 pandas 图中饼图的顺序?
How do I rearrange the order of pie slices in pandas plot?
我正在尝试重新排列饼图中饼图切片的顺序。我对 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
如果每个国家在您的数据框中只出现一次,您可以尝试 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()
我正在尝试重新排列饼图中饼图切片的顺序。我对 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
如果每个国家在您的数据框中只出现一次,您可以尝试 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()