0

I am analyzing chess games in python and am trying to generate a histogram of number of moves per game. The goal is to obtain something similar to this visualization, where there seems to be on average 70 moves per game:

histogram of moves

Currently I have an unordered dict:

{'106': 38,
 '100': 46,
 '65': 58,
 '57': 47,
 '54': 31,
 '112': 29,
 '93': 35,
 '91': 44,
 ...
 '109': 35,
 '51': 26}

where the keys denote number of moves, and values denote number of games.

I am finding it stupidly difficult to extract the dictionary data for plotting the histogram. I have tried extracting to a dataframe but am unable to get it in a matplotlib/seaborn readable format.

2 Answers2

0

Does this work for you?

import matplotlib.pyplot as plt
dict = {'106': 38,...}
plt.bar([int(d) for d in dict.keys()], dict.values())
plt.show()
Peter Schindler
  • 276
  • 1
  • 10
0

Firstly, we are going to sort your dictionary with dict comprehension:

d = {'106': 38,
 '100': 46,
 '65': 58,
 '57': 47,
 '54': 31,
 '112': 29,
 '93': 35,
 '91': 44,
 '109': 35,
 '51': 26}

sorted_d = {key:d[key] for key in sorted(d, key = lambda x: int(x))}

And now we display it with barplot:

import seaborn as sns
sns.barplot(x=list(sorted_d .keys()), y = list(d.sorted_d ()))

This is the result you get:

correct image

If you don't sort dictionary you get this:

enter image description here

Tugay
  • 2,057
  • 5
  • 17
  • 32