从打印语句数组中读取值以创建一个饼图 [英] Read the values from the print statement array to create a pie-chart

查看:83
本文介绍了从打印语句数组中读取值以创建一个饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

import matplotlib.pyplot as plt
students = [6,3,1,8,2]

a=[]
for s in students:
    a.append((s/20)*100)

values =[]
for b in a:
    values.append(b)
print(values)

# Want to grab values directly from the "print(values)" instead of copying them from the output.
values = [30, 15, 5 , 40, 10]  
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'red']

plt.pie(values, labels=[6,3,1,8,2], colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)

如两个"for循环"中所示,我正在获取该数组中每个学生的%值.我目前从"for循环"计算得出的输出是:

As shown in both "for loops", I am getting the % value for each of the student in that array. My current output from the "for loops" computation is:

[30.0, 15.0, 5.0, 40.0, 10.0]

而且,以下链接显示了我使用Piechart语法获得的饼图:

And, the piechart I get using the syntax for piechart is shown in the following link:

http://oi58.tinypic.com/68hued.jpg

我得到了想要的结果,但是我不想拥有values = [30, 15, 5 , 40, 10],因为我必须从输出中手动输入每个数字.

I get the results I want, but I don't want to have values = [30, 15, 5 , 40, 10] because I have to manually enter each number from the output.

如果我有50个数字,那么我将不输入每个数字.我可以,但这只是不干净.

If I have 50 numbers, then I am not going to enter each number. I could, but that is just not clean.

谢谢!

推荐答案

首先,您应该可以删除第二个for循环,除非它们是您包含第二个循环的特定原因.列表"a"已经存储了您所有的值,因此将列表复制到另一个列表是多余的.

First off, you should be able to remove your second for loop unless their is a specific reason you are including it. List 'a' already stores all your values, therefore it is redundant to copy the list to another list.

只要返回正确的列表,您的脚本似乎应该能够正确显示饼图中的值,而无需手动输入.您正在调用绘图语句中的值",该语句应该已经存储了上面循环中所需的所有百分比值.

It looks like your script should be able to display the values on the pie chart properly as is without manually entering them, as long as you are returning the correct list. You are calling on 'values' in the plotting statement, which should already store all the percentage values you need from the loop above.

您的代码应如下工作:

import matplotlib.pyplot as plt
students = [6,3,1,8,2]

values=[]
for s in students:
    values.append((s/20.)*100)

print values

colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'red']

plt.pie(values, labels=students, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90)
plt.show()

在pyhton 2.7中运行脚本时,"values"由于整数除法的结果而返回0的列表,用于百分比计算.如果这是问题所在,请确保使用.".在百分比计算中返回十进制而不是下限整数结果.如果您使用的是Python 3,则没有必要.

When running your script in pyhton 2.7, 'values' returned a list of 0s as a result of the integer division for your percent calculations. If this is the issue, make sure to use a '.' in your percentage calculation to return a decimal rather than floor integer result. If you are working in Python 3, this will not be necessary.

这篇关于从打印语句数组中读取值以创建一个饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆