I am developing a application using Tkinter for the interface, and then using pyplot from matplotlib to create a pie chart.
I have successfuly been able to display the data on a pie chart without a legend, such that the percentages are shown. Below is the relevant source code extract.
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()
I have also been able to display the same pie chart, with the legend but without the numerical values:
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()
However, I am unable to display both the legend and the numerical values on the pie chart, at the same time.
If I add "autopct='%1.1f%%'" field into the pie, text = plt.pie(…) line I get the following error:
"pie, text= plt.pie(values, labels=labels, explode = explode, autopct='%1.1f%%', shadow=True)
ValueError: too many values to unpack"
Best Answer
When you add
autopct
to the pie function, the returned format changes resulting in yourtoo many values to unpack
message being displayed. The following should work:Giving you the following output: