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

3
我正在使用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个回答

5
当您在饼图函数中添加autopct时,返回的格式会发生变化,导致显示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")

给您以下输出结果:

样本输出


这正是我正在寻找的!谢谢Martin。 - reyyez

1
根据文档,
如果 autopct 不是 none,pie 函数将返回元组 (patches, texts, autotexts)。
因此,您可以通过使用以下行使上述工作:
pie, texts, autotexts = plt.pie(values, labels=labels, explode=explode, shadow=True, autopct='%1.1f%%')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接