问题
Here is the code:
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)
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]
And, the piechart I get using the syntax for piechart is shown in the following link:
http://oi58.tinypic.com/68hued.jpg
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.
If I have 50 numbers, then I am not going to enter each number. I could, but that is just not clean.
Thanks!!
回答1:
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.
Your code should work as follows:
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()
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.
来源:https://stackoverflow.com/questions/32926202/read-the-values-from-the-print-statement-array-to-create-a-pie-chart