Search code examples
pythonmatplotlibpie-chart

Print exact variable values with percentage symbols on pie chart


enter image description here

I would like to represent on a pie chart, the exact same values of the column "Percentage Answers" with a percentage symbol (100 % instead of 100.0). I researched similar questions in Stackoverflow, and they seemed to use autopct. I don't seem to use it properly (I don't understand it neither) to display the same values of my column, with %.

Thanks in advance for your help!

Here is a small reproducible code :

# Import pandas library
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
 
# initialize list of lists
data = [['Basics 1', 100.0], ['Basics 2', 100.0], ['Basics 3', 40.0]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Course', 'Percentage Answers'])

# Plot teachers feedback percentages
my_labels= list(df['Course'])
plt.pie(df["Percentage Answers"], labels = my_labels, autopct='%0.0f%%')
plt.title("Percentage of Teacher's Feedback Participation")
plt.axis('equal')
plt.show()

Solution

  • You can use like this, i will show you my own example , but you can simply apply to your example

    import matplotlib.pyplot as plt
    import numpy
    
    
    # Pie chart, where the slices will be ordered and plotted counter-clockwise:
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs', 'Tgs', 'Lgs'
    sizes = [65, 30, 45, 10, 34, 44]
    
    dic = dict()
    for i in sizes:
        dic[numpy.round(i / sum(sizes) * 100,2)] = str(int(i)) + " %"
    
    def raw_value(val):
        return dic[numpy.round(val,2)]
    
    fig1, ax1 = plt.subplots()
    ax1.pie(sizes,labels=labels, autopct=raw_value)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    
    plt.show()