如何使用子图在 Python 中绘制具有变量类别的多个条形图?

How to draw multiple barcharts in Python with variable categories using subplot?

所以我的输入数据是两个字典 D1 和 D2,它看起来像这样:

D1 = {
'A':{'X1':1, 'X2':2},
'B':{'X3':3, 'X4':4,'X5':10},
...
'T':{'X100':30}
}
D2 = {
'A':{'X1':4, 'X2':2},
'B':{'X3':13, 'X4':2,'X5':8},
...
'T':{'X100':16}
}

更新:我手动画了一张图来展示我想要的东西。

D1和D2都有20个键(从A到T,我们称这些为主键),每个主键对应另一个具有相同键的字典,例如A对应另一个具有键X1的字典和X2(我们称这些为 X 键,因为它们都以 X 开头)。 我想在一个图中绘制一个 4 x 5 的条形图,每个条形图对应一个主键。 对于每个单独的图,我想绘制一个条形图,其中类别对应于 X 键。

现在我运行分为两个问题,任何对这两个问题的帮助将不胜感激。

第一个问题是,如您所见,每个类别中的 X 键数量不同,如何根据 X 键数量在条形图中创建动态条形图?我能想到的一种方法是根据 X 键名创建变量。

第二个问题是如何将这 20 个动态条形图分组到一个图中? 非常感谢!

您可以将字典转换为长格式数据框。然后使用 seaborn 的 sns.catplot() 绘制条形图网格:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

# first, create some test data with the given structure
mains = [*'ABCDEFGHIJKLMNOPQRST']
lengths = np.random.randint(2, 11, len(mains))
starts = np.append(0, lengths.cumsum())
D1 = {main: {f'X{i}': np.random.randint(2, 10) for i in range(s0, s1)}
      for main, s0, s1 in zip(mains, starts[:-1], starts[1:])}
D2 = {main: {f'X{i}': np.random.randint(2, 10) for i in range(s0, s1)}
      for main, s0, s1 in zip(mains, starts[:-1], starts[1:])}

# create a "long form" dataframe of the given dictionaries
df = pd.concat([pd.DataFrame({'Dictionary': ['D1'], 'main': [main], 'x': [x], 'Height': [val]})
                for main in D1.keys() for x, val in D1[main].items()] +
               [pd.DataFrame({'Dictionary': ['D2'], 'main': [main], 'x': [x], 'Height': [val]})
                for main in D2.keys() for x, val in D2[main].items()], ignore_index=True)

# draw a grid of barplots
g = sns.catplot(kind='bar', data=df, x='x', y='Height', hue='Dictionary', palette='spring',
                col='main', col_wrap=5, height=3, aspect=1.5, sharex=False)
g.set(xlabel='')  # remove superfluous x labels
plt.show()