如何基于患者就诊数据绘制符合需求的桑基图(Sankey Diagram)
桑基图实现患者就诊路径可视化方案
数据预处理步骤
先把原始数据整理成桑基图所需的**节点(nodes)和流量链路(links)**格式:
筛选首次就诊后的记录
定位每个患者的首次就诊节点,仅保留后续就诊数据:import pandas as pd # 假设你的数据集存储在df中 # 按患者分组,提取首次就诊次数 first_visit = df.groupby('pat_id')['contactnummer'].min().reset_index(name='first_contact') # 合并后筛选首次就诊后的记录 df_post_first = df.merge(first_visit, on='pat_id') df_post_first = df_post_first[df_post_first['contactnummer'] > df_post_first['first_contact']]整理流转链路与节点
按需求将症状组合(Combo2)作为箭头、治疗方案(treatment)作为节点,统计每个症状到对应治疗的患者流量:# 统计症状-治疗组合的唯一患者数(避免同一患者多次就诊重复计数) flow_counts = df_post_first.groupby(['Combo2', 'treatment'])['pat_id'].nunique().reset_index(name='value') # 生成所有节点(症状组合+治疗方案)的索引映射 all_nodes = pd.concat([flow_counts['Combo2'], flow_counts['treatment']]).unique() node_dict = {name: idx for idx, name in enumerate(all_nodes)} # 给每个症状组合分配专属颜色 from plotly.colors import qualitative combo_colors = {combo: qualitative.D3[i % len(qualitative.D3)] for i, combo in enumerate(flow_counts['Combo2'].unique())} # 构建链路数据 links = [] for _, row in flow_counts.iterrows(): links.append({ 'source': node_dict[row['Combo2']], 'target': node_dict[row['treatment']], 'value': row['value'], 'color': combo_colors[row['Combo2']] }) # 构建节点列表 nodes = [{'label': name} for name in all_nodes]
绘制桑基图
用Plotly的Sankey组件实现可视化,区分箭头与节点颜色:
import plotly.graph_objects as go fig = go.Figure(data=[go.Sankey( node = dict( pad = 15, thickness = 20, line = dict(color = "black", width = 0.5), label = [n['label'] for n in nodes], # 给治疗节点设置统一灰色,与症状节点区分 color = ['#cccccc' if label in df_post_first['treatment'].unique() else combo_colors[label] for label in all_nodes] ), link = dict( source = [link['source'] for link in links], target = [link['target'] for link in links], value = [link['value'] for link in links], color = [link['color'] for link in links] ) )]) fig.update_layout(title_text="首次就诊后症状组合到治疗的流转路径", font_size=10) fig.show()
关键调整说明
- 用
nunique('pat_id')统计流量,确保数据反映真实的患者流转,而非就诊次数 - 箭头颜色绑定症状组合,治疗节点用统一灰色,完全匹配你“区分症状箭头与治疗节点”的需求
- 如果需要展示跨就诊的连续路径(如前一次治疗→后一次症状→后一次治疗),可修改预处理逻辑:按
pat_id和contactnummer排序,将前一次的treatment作为源节点,当前Combo2作为中间节点,当前treatment作为目标节点,构建链式流转链路
内容的提问来源于stack exchange,提问作者RvS
相关产品推荐
相关产品推荐

