您可以将字典转换为长格式的数据帧。然后用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()