Search code examples
pythonmatplotlibgraphpie-chart

Pie chart, how to put percentages next to graph?


I was trying to create a pie chart with percentages next to the graph. The data that i have is the following.

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

And i´m trying to get something like this.

enter image description here


Solution

  • Try setting autopct to what you need:

    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")
    

    Output:

    enter image description here