【问题标题】:How do i get pie chart labels to line up with the correct values from dataframe?如何让饼图标签与数据框中的正确值对齐?
【发布时间】:2023-01-09 16:06:33
【问题描述】:

我的饼图显示正常,段的大小正确,但标签不在正确的位置。

# declaring exploding pie
explode = [0, 0.1, 0, 0, 0,0]
# define Seaborn color palette to use
palette_color = sns.color_palette('pastel')
  
# plotting data on chart
fig=plt.pie(combined_df.groupby(['Continent'])['total_consumption'].sum(), colors=palette_color,labels=combined_df['Continent'].unique(),
        explode=explode, autopct='%.0f%%', labeldistance=0.9,)
plt.show

应该绘制的值

Continent
Africa           227.0
Asia             128.7
Europe           431.9
North America    147.5
Oceania           42.5
South America     83.2

【问题讨论】:

  • 在您的代码中,您正在绘制值计数。你如何从计数中得到不是整数的the actual values
  • 谢谢,我已经纠正了那个错误,但问题仍然存在

标签: python pandas dataframe matplotlib data-analysis


【解决方案1】:

我怀疑是unique()value_counts()的返回结果顺序不一致。

返回的value_counts()是按计数排序的,unique()是按数组中出现的顺序排序的。

你可以试试这个:

value_cnts = combined_df['Continent'].value_counts()
fig = plt.pie(value_cnts, colors=palette_color, labels=value_cnts.index, 
    explode=explode, autopct='%.0f%%', labeldistance=0.9)

【讨论】:

  • 英雄所见略同。 +1
  • 解决了。谢谢你!
【解决方案2】:

尽量不要对 value_counts 上的值进行排序:

fig=plt.pie(combined_df['Continent'].value_counts(sort=False),  # <- do not sort
            colors=palette_color,
            labels=combined_df['Continent'].unique(),  # because unique is not sorted
            explode=explode, autopct='%.0f%%', labeldistance=0.9,)

演示:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

palette_color = sns.color_palette('pastel')
explode = [0, 0.1, 0, 0, 0,0]

np.random.seed(2023)
data = data = np.random.choice(
    ['Africa', 'Asia', 'Europe', 'North America', 'Oceania', 'South America'],
    p=(0.213989, 0.121324, 0.407146, 0.139046, 0.040064, 0.078431),
    size=1000
)
combined_df = pd.DataFrame({'Continent': data})

fig = plt.pie(combined_df['Continent'].value_counts(sort=False), 
              autopct='%.0f%%', labeldistance=0.9, 
              labels=combined_df['Continent'].unique(),
              colors=palette_color, explode=explode)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    相关资源
    最近更新 更多