matplotlib 如何添加线以链接堆叠条形图类别

rjzwgtxy  于 2023-02-16  发布在  其他
关注(0)|答案(1)|浏览(125)

我有一个两个变量的堆叠条形图。

ax = count[['new_category', "Count %", "Volume%"]].set_index('new_category').T.plot.bar(stacked=True) 
plt.xticks(rotation = 360)
plt.show()

我想用线连接类别,所以我的类别是用线连接的。

bhmjp9jg

bhmjp9jg1#

您可以循环遍历每个条形容器,然后遍历每个条形。连接条形顶部将给予所需的图:

from matplotlib import pyplot as plt
import pandas as pd

count = pd.DataFrame({'new_category': ['Cat A', 'Cat B'],
                      'Count %': [20, 30],
                      'Volume%': [15, 40]})
ax = count[['new_category', "Count %", "Volume%"]].set_index('new_category').T.plot.bar(stacked=True)
for bars in ax.containers:
    prev_x = None
    prev_y = None
    for bar in bars:
        x, y = bar.get_xy()
        w = bar.get_width()
        h = bar.get_height()
        if prev_x is not None:
            ax.plot([prev_x, x], [prev_y, y + h], ls=':', color='k', lw=0.5)
        prev_y = y + h
        prev_x = x + w
ax.legend(loc='upper left', bbox_to_anchor=[1.01, 1.01])
ax.tick_params(axis='x', rotation=0)
plt.tight_layout()
plt.show()

下面是另一个例子,使用seaborn创建的条:

from matplotlib import pyplot as plt
import seaborn as sns

flights = sns.load_dataset('flights')
flights['year'] = flights['year'].astype(str)
fig, ax = plt.subplots(figsize=(12, 5))
sns.histplot(data=flights, x='year', hue='month', weights='passengers',
             multiple='stack', palette='Set3', discrete=True, shrink=0.7, ax=ax)
for bars in ax.containers:
    prev_x = None
    prev_y = None
    for bar in bars:
        x, y = bar.get_xy()
        w = bar.get_width()
        h = bar.get_height()
        if prev_x is not None:
            ax.plot([prev_x, x], [prev_y, y + h], ls=':', color='k', lw=1)
        prev_y = y + h
        prev_x = x + w
sns.move_legend(ax, loc='upper left', bbox_to_anchor=[0.02, 1], ncol=2)
sns.despine()
ax.margins(x=0.01)
ax.set_ylabel('number of passengers')
ax.set_xlabel('')
plt.tight_layout()
plt.show()

相关问题