Python 3使用matplotlib显示百分比饼图,TypeError

时间:2016-08-04 16:07:04

标签: python matplotlib charts

我正在使用matplotlib制作一个只有2个段的简单饼图。当我在pie命令的开头添加变量'fracs'时,我得到关于“explode”参数的错误。这是我的代码:

import matplotlib.pyplot as plt

dataFile = open("data.txt") #open the file with the data
bigData = dataFile.readlines() #read it into a variable
bigData2 = [] # make a second list

for line in bigData: #iterate through bigData and make bigData2, a list with lists in it ( 2D list? )
    aData = line.split(",")
    bigData2.append(aData)

transfer = [] #make transfer list holder
nonTransfer = [] #make nonTransfer list holder

for i in bigData2: #iterate through bigData2 and sort based on contents
    if i[2] == "Request Transferred\n":
        transfer.append(i)
    if i[2] != "Request Transferred\n":
        nonTransfer.append(i)

trans = len(transfer) #get lengths of the lists
nTrans = len(nonTransfer)

total = trans+nTrans

percentTrans = int((trans/total)*100) #makes percentage values
percentnTrans = int((nTrans/total)*100)

fracs = [percentTrans,percentnTrans] #make fraction variable
print(percentnTrans, ",", percentTrans)

#Setup and make the pie chart

labels = 'transfer', 'nonTransfer'
sizes = trans, nTrans
colors = 'red', 'blue'
explode = (0, 0.1)
plt.pie(fracs , sizes, explode=explode, labels=labels, colors=colors, shadow=True, startangle=90)
plt.axis('equal')
plt.show()

在我看来,大部分内容都可以忽略。我觉得可能是问题的根源是'fracs'定义时和plt.pie()行。

回溯如下:

  

追踪(最近一次通话):   92,7文件“C:/Users/LewTo002/Desktop/serReq/dataEdit.py”,第37行,   在       plt.pie(fracs,sizes,explode = explode,labels = labels,colors = colors,shadow = True,startangle = 90)TypeError:pie()got   参数'explode'的多个值

我的工作基于(http://matplotlib.org/1.2.1/examples/pylab_examples/pie_demo.html)和(http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html)在本文档的帮助下(http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie

经过进一步的反思,我确实觉得我定义'压裂'的方式是罪魁祸首,但我不完全确定我是怎么(或者是否)在那里出错了。我很感激您的时间和帮助。

1 个答案:

答案 0 :(得分:1)

根据matplotlib文档,pie()函数接受一个参数,然后是关键字参数。

matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None,    pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)

在您的示例中,您使用以下调用

调用pie()函数
plt.pie(fracs , sizes, explode=explode, labels=labels, colors=colors, shadow=True, startangle=90)

基本上,pie()函数只需要一个普通参数,但因为你提供了两个(fracssizes),你的第二个函数会被分配给关键字explode。因此,Python会引发以下错误TypeError: pie() got multiple values for argument 'explode',因为您要将值分配给explode两次。

编辑1

如果你想要每个楔形中的百分比,那么在调用autopct函数时使用pie()关键字参数。这显示在example中,并在documentation中解释。

  

autopct:[无|格式字符串|格式功能]

  如果不是None,则是用于用其数值标记楔形的字符串或函数。标签将放在楔子内。如果是格式字符串,则标签为fmt%pct。如果它是一个函数,它将被调用。

每个楔形中显示的值将与fracs中给出的值相对应。如果您想使用sizes中定义的其他标签,那么我猜您必须在顶部绘制第二个pie()并使用这些值,然后设置colors kwarg到None,只显示标签。

相关问题