首页 > 解决方案 > 如何从字典中的字典创建子图条形图

问题描述

我需要制作以下字典的条形图的子图:dict1 = {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}, 45:{0: 1, 1: 4, 2: 2, 3: 0, 4: 0}}

This was my (not correct) code:
fig, ax = plt.subplots(2,1)
for nr in dict1: 
        ax[list(dict1.keys()).index(nr),1].plot(list(dict1[nr].keys()), list(dict1[nr].values()), kind='bar')
        plt.tight_layout()
        plt.show

你能帮我吗?提前致谢。

标签: pythonmatplotlib

解决方案


问题中的代码有很多错误。两种选择:

Matplotlib 风格的绘图

import matplotlib.pyplot as plt

dict1 = {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}, 45:{0: 1, 1: 4, 2: 2, 3: 0, 4: 0}}

fig, axs = plt.subplots(len(dict1.keys()))
for (k, d), ax in zip(dict1.items(), axs):
    ax.bar(*zip(*d.items()))
    ax.set_title(k)

fig.tight_layout()
plt.show()

在此处输入图像描述

熊猫风格的绘图

import pandas as pd
import matplotlib.pyplot as plt

dict1 = {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}, 45:{0: 1, 1: 4, 2: 2, 3: 0, 4: 0}}
df = pd.DataFrame(dict1)

df.plot.bar(subplots=True)
    
plt.tight_layout()
plt.show()

在此处输入图像描述


推荐阅读