Python: Best way to visualize dict of dicts

2019-08-23 04:50发布

问题:

I want to visualize the following dict of dicts

players_info = {'Afghanistan': {'Asghar Stanikzai': 809.0,
  'Mohammad Nabi': 851.0,
  'Mohammad Shahzad': 1713.0,
  'Najibullah Zadran': 643.0,
  'Samiullah Shenwari': 774.0},
 'Australia': {'AJ Finch': 1082.0,
  'CL White': 988.0,
  'DA Warner': 1691.0,
  'GJ Maxwell': 822.0,
  'SR Watson': 1465.0},
 'England': {'AD Hales': 1340.0,
  'EJG Morgan': 1577.0,
  'JC Buttler': 985.0,
  'KP Pietersen': 1176.0,
  'LJ Wright': 759.0}}

Currently I am using the following way but with large dict it is making a clutter which I don't want.

import pandas as pd
import matplotlib.pyplot as plt

pd.DataFrame(players_info).plot.bar()
plt.show()

Please suggest a better way of visualizing it. Thanks

回答1:

You first need a better dataframe structure out of your dict.

df = pd.DataFrame([(i,j,players_info[i][j]) for i in players_info.keys() for j in players_info[i].keys()], columns=["country", "player", "score"])

Then, you may use the plotting like below:

fig = plt.figure(figsize=(15,5))
ax = sns.barplot(x="player", y="score", hue="country" ,data=df)
plt.xticks(rotation=45)
plt.show()

Output:



回答2:

I suggest using heatmap.

import pandas as pd
import seaborn as sns
sns.set(rc={"figure.figsize":(12,8)})

df = pd.DataFrame(players_info)
g = sns.heatmap(df, cmap="Blues", annot=True, fmt='g')
g.get_figure().savefig("heatmap.png")

Output: