Python使用pyalluvial实现堆叠柱状图与冲积图同图展示问题
pyalluvial堆叠柱状图+冲积图组合实现方案
问题原因
- 现有代码传入的
Point 1/2/3列为占比数值,不符合pyalluvial的输入要求:xaxis_names指定的列应为分类标签,用于标记每个流在对应x轴节点的分组归属 - 固定配置
y_name='Ove'会强制所有x轴节点的流高度都基于Ove字段数值计算,无法实现每个Point节点独立的100%堆叠展示
解决代码
新版本pyalluvial(v0.1.7及以上)
import pandas as pd import pyalluvial.alluvial as alluvial import matplotlib.pyplot as plt # 构造长表存储每个分组在各节点的占比 df = pd.DataFrame({ 'Group': [1, 2, 3] * 4, 'node': ['Ove']*3 + ['Point 1']*3 + ['Point 2']*3 + ['Point 3']*3, 'value': [0.7, 0.2, 0.1, 0.8, 0.1, 0.1, 0.6, 0.2, 0.2, 0.7, 0.3, 0.0] }) ax = alluvial.plot( df=df, x_axis_col='node', stratum_col='Group', weight_col='value', alluvium_col='Group', # 指定x轴节点顺序 x_order=['Ove', 'Point 1', 'Point 2', 'Point 3'], # 开启百分比堆叠,每个节点总高度为1 stratum_type='percent' ) ax.set_ylabel('占比') plt.show()
旧版本pyalluvial
旧版本不支持长表输入,可通过widths参数手动指定每个节点各分组的高度:
import pandas as pd import pyalluvial.alluvial as alluvial import matplotlib.pyplot as plt df = pd.DataFrame({ 'Group': [1, 2, 3], 'Ove': [1, 2, 3], 'Ove_weight': [0.7, 0.2, 0.1], 'Point 1': [1, 2, 3], 'Point1_weight': [0.8, 0.1, 0.1], 'Point 2': [1, 2, 3], 'Point2_weight': [0.6, 0.2, 0.2], 'Point 3': [1, 2, 3], 'Point3_weight': [0.7, 0.3, 0.0], }) ax = alluvial.plot( df=df, xaxis_names=['Ove', 'Point 1', 'Point 2', 'Point 3'], alluvium='Group', # 按顺序传入每个节点各分组的高度 widths=[df['Ove_weight'], df['Point1_weight'], df['Point2_weight'], df['Point3_weight']] ) ax.set_ylabel('占比') plt.show()
内容的提问来源于stack exchange,提问作者Chopin
相关产品推荐
相关产品推荐

