绘制一个系列饼图

问题描述 投票:1回答:2

我有一个系列df2,我想用饼图绘制

 Index
Friday       2
Thursday     2
Wednesday    3

我试过了

 colors =  ["#E13F29", "#D69A80", "#D63B59", "#AE5552", "#CB5C3B", "#EB8076", "#96624E"]
df2.plot().pie(df2['counts'],df2.index,shadow=False,colors=colors, explode=(0, 0, 0, 0, 0.15), startangle=90,autopct='%1.1f%%', )
# View the plot drop above
pyplot.axis('equal')
# View the plot
pyplot.tight_layout()
pyplot.show()

ValueError:无法将字符串转换为float:'Wednesday'

python pandas matplotlib plot pie-chart
2个回答
2
投票

考虑一下pd.Series -

s

Index
Monday       2
Tuesday      4
Wednesday    5
Thursday     2
Friday       1
Saturday     6
Sunday       3
Name: counts, dtype: int64

现在,在pd.Series.plot.pie列上调用counts -

s.plot.pie(y=df.index,
           shadow=False,
           colors=colors, 
           explode=(0, 0, 0, 0, 0.15, 0, 0),   # exploding 'Friday'
           startangle=90,
           autopct='%1.1f%%')

plt.axis('equal')
plt.tight_layout()
plt.show()

不要打电话给plot()!在pie上打电话给plot

enter image description here


如果您需要按工作日排序索引,请务必将其转换为pd.Categorical -

cat = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday']

df.index = pd.Categorical(df.index, categories=cat, ordered=True)
df = df.sort_index()

然后,您可以如上图所示进行绘图。


0
投票

我们试试这个:

colors =  ["#E13F29", "#D69A80", "#D63B59", "#AE5552", "#CB5C3B", "#EB8076", "#96624E"]
df.groupby(df.Index.dt.strftime('%A'))['Index'].count().plot.pie(figsize=(5,5),colors=colors,
                                                                 explode=(0,0,0,0.1),
                                                                 startangle=90,
                                                                 autopct='%1.1f%%')

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.