Search code examples
matplotlibpie-chart

Creating a Pie Chart on a single row but Multiple Columns in Matplotlib


Issue

I have cumulative totals in row 751 in my dataframe

I want to create a pie chart with numbers and % on just line 751

This is my code

import matplotlib.pyplot as plt
%matplotlib notebook
data = pd.read_csv('cleaned_df.csv')

In my .csv I have the following Columns

A,B,C,D,E,F

Rows under Columns(Letters) Rows( Numbers )
A= 123456
B= 234567
C= 345678
D= 456789
E= 56789
F= 123454

Lets say I want to create a pie chat with only Column B & D and F and the last row of numbers which would be row 6 (678994)

How do I go about that ?


Solution

  • Possible solution is the following:

    import matplotlib.pyplot as plt
    import pandas as pd
    
    # set test data and create dataframe
    data = {"Date": ["01/01/2022", "01/02/2022", "01/03/2022", "01/04/2022", ], "Male": [1, 2, 3, 6], "Female": [2, 2, 3, 7], "Unknown": [3, 2, 4, 9]}
    df = pd.DataFrame(data)
    

    Returns (where 3 is the target row for chart)

    enter image description here

    # set target row index, use 751 in your case
    target_row_index = 3
    
    # make the pie circular by setting the aspect ratio to 1
    plt.figure(figsize=plt.figaspect(1))
    
    # specify data for chart
    values = df.iloc[target_row_index, 1:]
    labels = df.columns[1:]
    
    # define function to format values on chart
    def make_autopct(values):
        def my_autopct(pct):
            total = sum(values)
            val = int(round(pct*total/100.0))
            return '{p:.2f}%  ({v:d})'.format(p=pct,v=val)
        return my_autopct
    
    plt.pie(values, labels=labels, autopct=make_autopct(values))
    plt.show()
    

    Shows

    enter image description here