Skip to content Skip to sidebar Skip to footer

Read The Values From The Print Statement Array To Create A Pie-chart

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

Solution 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)

printvalues

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.

Post a Comment for "Read The Values From The Print Statement Array To Create A Pie-chart"