-1

My dictionary look like this:

{'come': 101, 'con': 101, 'si': 101, 'ha': 104, 'una': 107, 
 'quindi': 114, 'le': 119, 'poi': 128, 'io': 129, 'per': 147, 
 'sono': 155, 'in': 175, 'ho': 179, 'il': 200, 'mi': 245, 
 'la': 247, 'non': 265, 'un': 270, 'di': 310, 'che': 377}

I want to plot a bar chart which shows each word sorted (in ascending order) by it's value. How would I do this? I have tried sorting the dictionary myself and then plotting, however the bars in the graph aren't sorted

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
Seb Cooper
  • 1
  • 1
  • 2
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Matthew Miles Nov 04 '20 at 16:59

1 Answers1

2

If you consider additional packages, let's try pandas

import pandas as pd
pd.Series(d).sort_values(ascending=False).plot.bar()

Output:

enter image description here

If Pandas is not an option, you can use Python approach:

# sort the dictionary by values, return a list of pairs
sorted_vals = sorted(d.items(), key=lambda x: (-x[1],x[0]))

plt.bar([x[0] for x in sorted_vals], [x[1] for x in sorted_vals])

and get pretty much the same plot.

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74