【问题标题】:can I represent the result of a counter with matplolib?我可以用 matplotlib 表示计数器的结果吗?
【发布时间】:2022-01-07 07:24:32
【问题描述】:

大家好,我想代表以下计数器的结果:

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':......

我尝试使用 matplotlib 来表示结果,但我找不到如何做到这一点。 这是我尝试的:

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

谢谢

【问题讨论】:

  • 什么不能用这个方法......看起来它应该对我有用
  • 您返回contador,然后再次返回contadas, contador,然后尝试绘制图表。您的方法在绘制图表之前返回值。

标签: python matplotlib counter imaging data-representation


【解决方案1】:

这是使用给定 Counter 值的条形图。

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

输出:

【讨论】:

    【解决方案2】:
    >>> from matplotlib import pyplot
    >>> from collections import Counter
    >>> data = Counter("aaabbbbccddde")
    >>> pyplot.bar(*zip(*data.most_common()))
    <BarContainer object of 5 artists>
    >>> pyplot.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多