gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:04 24 4
gpt4 key购买 nike

我正在开发一个使用 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")

为您提供以下输出:

sample output

关于python - 在饼图上显示带有图例的数字 - Tkinter、Pyplot、Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34765236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com