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()
1条答案
按热度按时间bhmjp9jg1#
您可以循环遍历每个条形容器,然后遍历每个条形。连接条形顶部将给予所需的图:
下面是另一个例子,使用seaborn创建的条: