在饼图上显示带有图例的数字 - Tkinter,Pyplot,Matplotlib

时间:2016-01-13 11:16:19

标签: python matplotlib tkinter pie-chart

我正在使用Tkinter为界面开发一个应用程序,然后使用matplotlib中的pyplot创建一个饼图。

我已成功地在没有图例的饼图上显示数据,从而显示百分比。以下是相关的源代码摘录。

labels = ["Oranges", "Bananas", "Apples", "Kiwis", "Grapes", "Pears"]
values = [0.1, 0.4, 0.1, 0.2, 0.1, 0.1]

 # now to get the total number of failed in each section
actualFigure = plt.figure(figsize = (8,8))
actualFigure.suptitle("Fruit Stats", fontsize = 22)

#explode=(0, 0.05, 0, 0)
# as explode needs to contain numerical values for each "slice" of the pie chart (i.e. every group needs to have an associated explode value)
explode = list()
for k in labels:
    explode.append(0.1)

pie= plt.pie(values, labels=labels, explode = explode, shadow=True)

canvas = FigureCanvasTkAgg(actualFigure, self)
canvas.get_tk_widget().pack()
canvas.show()

我也能够使用图例显示相同的饼图,但没有数值:

labels = ["Oranges", "Bananas", "Apples", "Kiwis", "Grapes", "Pears"]
values = [0.1, 0.4, 0.1, 0.2, 0.1, 0.1]

 # now to get the total number of failed in each section
actualFigure = plt.figure(figsize = (10,10))
actualFigure.suptitle("Fruit Stats", fontsize = 22)

#explode=(0, 0.05, 0, 0)
# as explode needs to contain numerical values for each "slice" of the pie chart (i.e. every group needs to have an associated explode value)
explode = list()
for k in labels:
    explode.append(0.1)

pie, text= plt.pie(values, labels=labels, explode = explode, shadow=True)
plt.legend(pie, labels, loc = "upper corner")

canvas = FigureCanvasTkAgg(actualFigure, self)
canvas.get_tk_widget().pack()
canvas.show()

但是,我无法同时在饼图上同时显示图例和数值。

如果我将“autopct ='%1.1f %%'”字段添加到饼中,text = plt.pie(...)行我会收到以下错误:

“pie,text = plt.pie(values,labels = labels,explode = explode,autopct ='%1.1f %%',shadow = True) ValueError:解包“

的值过多

2 个答案:

答案 0 :(得分:5)

当您将autopct添加到pie function时,返回的格式会发生变化,从而导致显示您的too many values to unpack消息。以下应该有效:

pie = plt.pie(values, labels=labels, explode=explode, shadow=True, autopct='%1.1f%%')
plt.legend(pie[0], labels, loc="upper corner")

给你以下输出:

sample output

答案 1 :(得分:1)

根据文件,

  

如果 autopct 不是none,则pie返回元组(补丁文本 autotexts )。< / p>

因此,您可以使用以下行完成上述工作:

pie, texts, autotexts = plt.pie(values, labels=labels, explode=explode, shadow=True, autopct='%1.1f%%')