Python: Best way to visualize dict of dicts

可紊 提交于 2020-01-06 04:45:06

问题


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:



来源:https://stackoverflow.com/questions/50614222/python-best-way-to-visualize-dict-of-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!