can I represent the result of a counter with matplolib?

36 Views Asked by At

Hello everyone i wanr to represent the following result of a counter:

Counter({'U.S.': 852, 'U.S.S.R/Russia': 273, 'Japan': 20, 'France': 18, 'Canada': 18, 'Germany': 16, 'China': 14, 'Italy': 13, 'U.K./U.S.': 6, 'Switzerland': 4, 'Australia':......

I try to use matplotlib to represent the results but i cant find how can i do this. That what i try:

def contador_nacionalidades(datos):
    contadas={}
    numero_astronautas=[(e.nacionalidad) for e in datos]
    contador= Counter(numero_astronautas)
    return contador
    contador.sort(key=lambda x: x[0], reverse=True)
    contadas=contador
    return contadas, contador
    plt.bar(contadas.keys(), contadas.values())
    plt.show()

Thanks

2

There are 2 best solutions below

0
arshovon On

Here is a Barchart using the given Counter values.

from collections import Counter
import matplotlib.pyplot as plt

data = Counter({'U.S.': 852, 'U.S.S.R/Russia': 273, 'Japan': 20, 'France': 18,
                'Canada': 18, 'Germany': 16, 'China': 14, 'Italy': 13,
                'U.K./U.S.': 6, 'Switzerland': 4})

countries = list(data.keys())
values = list(data.values())

fig = plt.figure(figsize=(10, 5))

# creating the bar plot
plt.bar(countries, values, color='maroon',
        width=0.4)

plt.xlabel("Countries")
plt.ylabel("Values")
plt.title("Bar chart from counter object")
plt.show()

Output:

output

0
Joran Beasley On
>>> from matplotlib import pyplot
>>> from collections import Counter
>>> data = Counter("aaabbbbccddde")
>>> pyplot.bar(*zip(*data.most_common()))
<BarContainer object of 5 artists>
>>> pyplot.show()

enter image description here