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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With