Py学习  »  Python

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

yondchang • 3 年前 • 1617 次点击  

所以我的输入数据是两个字典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}
}

更新:我手动绘制一张图片来显示我想要的东西。

enter image description here

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

现在我遇到了两个问题,如果能在这两个问题上提供帮助,我将不胜感激。

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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131330
文章 [ 1 ]  |  最新文章 3 年前
JohanC
Reply   •   1 楼
JohanC    3 年前

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

sns.catplot grid of bar plots from dictionaries