【问题标题】:How can I plot a counter in order?如何按顺序绘制计数器?
【发布时间】:2021-12-09 18:01:42
【问题描述】:

我有一个 Python 计数器,它存储元组键和 int 值,看起来像这样:

Counter({(0,): 31118, (160,): 7931, (229,): 7183, (225,): 5668, (48,): 5667, ... , (171,): 19})

里面的项目是按它们的值降序排列的,我试图以同样的方式绘制它们。

我尝试使用 plt.bar 时只使用前 10 个值(使用完整集时它是相同的随机顺序):

keylist = list()

for key in countersum.keys():
    keylist.append(str(key))

plt.bar(keylist[:10], list(countersum.values())[:10])
plt.show()

这给了我下图:

问题是为什么它没有排序,我怎样才能使它按降序排列到它们的值?

【问题讨论】:

    标签: python plot count bar-chart counter


    【解决方案1】:

    IIUC,您需要首先根据值对dict 进行排序,然后将它们绘制如下:

    >>> dct = {(171,): 19, (0,): 31118, (225,): 5668, (160,): 7931, (48,): 5667, (229,): 7183}
    
    >>> srt_dct = dict(sorted(dct.items(), key=lambda item: item[1], reverse=True))
    
    >>> srt_dct
    {(0,): 31118,
     (160,): 7931,
     (229,): 7183,
     (225,): 5668,
     (48,): 5667,
     (171,): 19}
    

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 2021-10-06
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多