2016-01-13 335 views
3

我正在开发一个使用Tkinter作为接口的应用程序,然后使用matplotlib的pyplot创建饼图。在饼图上显示带有图例的数字 - Tkinter,Pyplot,Matplotlib

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

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 %%'” 栏进入我得到以下错误的馅饼,文本= plt.pie(...)线:

“馅饼,文本= PLT .pie(值,标签=标签,爆炸=爆炸,autopct = '%1.1F %%',阴影= TRUE) ValueError异常:值过多解压”

回答

4

当您添加autopctpie 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

+0

这就是我正在寻找的!谢谢你,马丁。 – reyyez

1

根据该文件,

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

因此可以使上述工作通过以下line:

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