Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate pie chart using dict_values in Python 3.4?

I wanted the frequency of numbers in a list which I got using Counter library. Also, I got the keys and values using keys = Counter(list).keys() and values = Counter(list).values() respectively, where list is the list of numbers. Their output are in following form:

dict_keys(['0.2200', '0.2700', '0.6200', '0.3000', '0.2500', '0.3400', '0.5600', '0.3900', '0.5400', '0.5500', '0.7500', '0.4100', '0.2800', '0.4200', '0.3800', '0.6600', '0.2000', '0.5200', '0.7200'])

and, dict_values([15, 3, 6, 13, 6, 3, 1, 3, 3, 5, 4, 14, 8, 5, 3, 5, 11, 3, 9])

Now I want to generate a pie-chart using keys and values which i did it in following way:

import matplotlib.pyplot as pyplot
pyplot.axis("equal")
pyplot.pie(float(values),labels=float(keys),autopct=None)
pyplot.show()

But, I get the error as:

TypeError: float() argument must be a string or a number, not 'dict_values'

Is there any way to convert dict_values to string or number as the function used to generate pie chart only accepts string or number?

like image 897
jraj Avatar asked Dec 20 '22 11:12

jraj


1 Answers

You need to loop through the values and convert them individually to floats:

pyplot.pie([float(v) for v in values], labels=[float(k) for k in keys],
           autopct=None)

The [expression for target in iterable] is called a list comprehension and produces a list object.

I'd not create the Counter() twice; create it just once and reuse:

counts = Counter(yourlist)
pyplot.pie([float(v) for v in counts.values()], labels=[float(k) for k in counts],
           autopct=None)
like image 83
Martijn Pieters Avatar answered Jan 17 '23 04:01

Martijn Pieters