如何将线添加到链接的堆叠条形图类别

huangapple go评论68阅读模式
英文:

How to addline to link stacked bar plot categories

问题

我想要连接类别之间的线条,以便我的类别之间可以用线连接。

英文:

I have a stacked bar chart for two variables.

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

I want to connect the categories with lines, so my categories are connected with lines.

如何将线添加到链接的堆叠条形图类别

答案1

得分: 2

以下是您要的翻译:

You could loop through each of the bar containers, and then through each of the bars. Connecting the bar tops should give the desired plot:

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()

如何将线添加到链接的堆叠条形图类别

Here is another example, using bars created by 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()

如何将线添加到链接的堆叠条形图类别

英文:

You could loop through each of the bar containers, and then through each of the bars. Connecting the bar tops should give the desired plot:

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()

如何将线添加到链接的堆叠条形图类别

Here is another example, using bars created by 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()

如何将线添加到链接的堆叠条形图类别

huangapple
  • 本文由 发表于 2023年2月14日 05:25:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定