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

displaying numbers with legend on pie chart - Tkinter, Pyplot, Matplotlib

我正在开发一个使用 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%%'" 字段添加到 pie, text = plt.pie(...) 行中,我会收到以下错误:

"pie, text= plt.pie(values, labels=labels, explode=explode, autopct='%1.1f%%', shadow=True) ValueError:要解压的值太多

当您将 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")

为您提供以下输出:

根据文档,

If autopct is not none, pie returns the tuple (patches, texts, autotexts).

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

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