饼图,如何将百分比放在图表旁边?

2024-10-01 02:39:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个饼图,图表旁边有百分比。我掌握的数据如下

users = [80, 40, 1000, 300, 50, 80, 10]
os = ['MacOS', 'Chrome', 'Windows', 'Linux', 'Devian', 'Ubuntu', 'Arch Linux']

我正试图得到这样的东西

enter image description here

谢谢你的帮助


Tags: 数据osubuntulinuxwindows图表macoschrome
2条回答

尝试将autopct设置为所需:

plt.pie(users, 
        labels=os, 
        explode=[0, 0, 0.05, 0, 0, 0, 0],
        pctdistance = 1.2, 
        labeldistance = 1.4,
        autopct=lambda x: f'{x:.1f}%\n({(x/100)*sum(users):.0f} users)',
        textprops={"family": "Arial", "size": 12},
        radius = 2,
        colors = ["#9BC2E6", "#FF6600", "#F4B084", "#00B050", "#C6E0B4", "#8633FF", "#CCCCFF"]
        )
plt.legend(loc="best", bbox_to_anchor=(2.5,0), title="Operating systems")

输出:

enter image description here

尝试使用plotly.express

import plotly.express as px
 
users = [80, 40, 1000, 300, 50, 80, 10]
os = ['MacOS', 'Chrome', 'Windows', 'Linux', 'Devian', 'Ubuntu', 'Arch Linux']
 
fig = px.pie(values=users, names=os, 
             color_discrete_sequence=px.colors.sequential.RdBu)
 
fig.update_traces(textposition='outside', 
                  textinfo='percent+label+value',
                  marker=dict(line=dict(color='#FFFFFF', width=2)),
                  textfont_size=12)
 
fig.show()

结果非常好:

enter image description here

相关问题 更多 >