Search code examples
pythonpandaspie-chart

how to plot a pie chart?


I have data like:

Machine_id Cycling Idle
81091001 41000000000 19000000000
81091001 40000000000 19000000000
81091001 41000000000 19000000000
81091001 41000000000 20000000000
81091001 41000000000 19000000000

Code for plotting Pie chart :

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(palette='Paired')

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

df = df.set_index('Machine_id')

for ind in df.index:
     fig, ax = plt.subplots(1,1)
     fig.set_size_inches(5,5)
     df.iloc[ind].plot(kind='pie', ax=ax, autopct='%1.1f%%')
     ax.set_ylabel('')
     ax.set_xlabel('')

I am getting a error here like:

IndexError: single positional indexer is out-of-bounds

Then how a pie chart can be formed for Cycling v/s Idle in pandas each Machine_id wise ?


Solution

  • Here is your problem solved:

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    sns.set(palette='Paired')
    
    df = pd.read_csv('sample1.csv')
    
    #df = df.set_index('Machine_id')  comment this
    
    for ind in df.index:
         fig, ax = plt.subplots(1,1)
         fig.set_size_inches(5,5)
         df.iloc[ind].plot(kind='pie', ax=ax, autopct='%1.1f%%')
         ax.set_ylabel('')
         ax.set_xlabel('')
         fig.show()   #plot/show final results
    

    another way, to consider individual chart with Cycling and Idle time per row. A Pie Chart for each line. (Maybe Pie Charts are not the best way to illustrate this but any way)

    Ref. https://matplotlib.org/api/pyplot_api.html

    import csv as csv
    import matplotlib.pyplot as plt
    
    colors = ['r', 'g']
    
    with open('sample1.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("Machine ID: " + row[0])  #title is here UPDATED
                plt.pie(slices, labels=activities, colors=colors, startangle=90, autopct='%.1f%%')
                plt.show()
    
            i += 1