Search code examples
pythonplotcountbar-chartcounter

How can I plot a counter in order?


I have a Python Counter that stores tuple keys and int values and looks something like this:

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

The items inside are in descending order of their values and I am trying to plot them the same way.

I tried using plt.bar while only using the first 10 values (it is in the same random order when using the full set):

keylist = list()

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

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

Which gives me the following diagram: enter image description here

The question is why is it not ordered and how can I make it so it plots in descending order to their values?


Solution

  • IIUC, You need first sort dict base on values then plot them like below:

    >>> 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}