Search code examples
pythonpandaspie-chart

plotting pie chart from csv data?


For data of car performance such as:

 Model  Running  Rest  
 1      10       14   
 1      11       13  
 1      12       12  
 2       9       15  
 2      10       14

how to plot Running and Rest each value plot here and also case like for 1st three rows since Model no is same?

import pandas as pd
import matplotlib.pyplot as plt  

df = pd.read_csv('performance.csv')

df.pie(x='Running', y='Rest', autopct='%1.1f%%', shadow=True, startangle=140))

After seeing few answers on stackoverflow I proceeded as:

import csv as csv
import matplotlib.pyplot as plt

colors = ['r', 'g']

with open('performance.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')

i = 0

for row in readCSV:
    if i == 0:
        activities = [row[1], row[2]]
        title = row[0]
    else:
        slices = [row[1], row[2]]
        plt.title("Model: " + row[0])  
        plt.pie(slices, labels=activities, colors=colors, startangle=90, autopct='%.1f%%')
        plt.show()

    i += 1

This code gives me each rows value of Running and Rest as a pie chart.

But how to get pie chart for say 1st three rows where Model column value is same?


Solution

  • Using your original df you can do something like:

    In []:
    df[['Running', 'Rest']].groupby(df.Model).plot.pie(subplots=True, autopct='%.1f%%')
    
    Out[]:
    

    enter image description here enter image description here