从CSV数据绘制饼图?

时间:2018-07-28 03:31:39

标签: python pandas pie-chart

有关汽车性能的数据,例如:

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

如何在此处绘制RunningRest每个值的图,以及由于Model的不同,第三个三行的情况也一样?

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

看到关于stackoverflow的几个答案后,我的操作如下:

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

此代码为我提供了RunningRest的每一行值,作为饼图。

但是如何获得说Model列值相同的前三行的饼图?

1 个答案:

答案 0 :(得分:3)

使用原始的df,您可以执行以下操作:

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

Out[]:

enter image description here enter image description here