mcpField
S
sankey-diagram-creator

sankey-diagram-creator

github.com/dkyazzentwatwa数据与数据库12461 次安装29 周前更新
代码仓库

关于 sankey-diagram-creator

sankey-diagram-creator 是一个 Python 工具,可将流量数据转为交互式桑基图。它支持字典、DataFrame 和 CSV 输入,并提供节点与连线样式设置及 HTML、PNG、SVG 导出。

主要功能

  1. 01读取字典、DataFrame 或 CSV
  2. 02生成带悬停详情的交互式图表
  3. 03自定义节点标签、颜色和位置
  4. 04设置连线颜色、透明度和标签
  5. 05导出交互式 HTML、PNG 或 SVG

适用场景

  1. 01可视化收入与支出流向
  2. 02绘制能源从来源到用途的转移
  3. 03展示用户旅程阶段及流失
  4. 04呈现多层级数据管道

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dkyazzentwatwa/chatgpt-skills --skill sankey-diagram-creator

安装后在 Claude Code 中输入/sankey-diagram-creator确认已加载。

附带文件scripts/requirements.txtscripts/sankey_creator.py

详细介绍

Sankey 图创建器

创建交互式 Sankey 图,以可视化类别之间的流动、转移和关系。非常适合展示预算流、能源转移、用户旅程和数据管道。

快速开始

from scripts.sankey_creator import SankeyCreator

# From dictionary
sankey = SankeyCreator()
sankey.from_dict({
    'source': ['A', 'A', 'B', 'B'],
    'target': ['C', 'D', 'C', 'D'],
    'value': [10, 20, 15, 25]
})
sankey.generate().save_html("flow.html")

# From CSV
sankey = SankeyCreator()
sankey.from_csv("flows.csv", source="from", target="to", value="amount")
sankey.title("Budget Flow").generate().save_html("budget.html")

功能

  • 多种输入源:字典、DataFrame 或 CSV 文件
  • 交互式输出:悬停时显示流量详情工具提示
  • 节点自定义:颜色、标签、位置
  • 链接样式:颜色、不透明度、标签
  • 导出格式:HTML(交互式)、PNG、SVG
  • 自动着色:自动分配颜色或使用自定义方案

API 参考

初始化
sankey = SankeyCreator()
数据输入方法
# From dictionary
sankey.from_dict({
    'source': ['A', 'A', 'B'],
    'target': ['X', 'Y', 'X'],
    'value': [10, 20, 15]
})

# From CSV file
sankey.from_csv(
    filepath="data.csv",
    source="source_col",
    target="target_col",
    value="value_col",
    label=None  # Optional: column for link labels
)

# From pandas DataFrame
import pandas as pd
df = pd.DataFrame({
    'from': ['A', 'B'],
    'to': ['C', 'C'],
    'amount': [100, 200]
})
sankey.from_dataframe(df, source="from", target="to", value="amount")

# Add individual flows
sankey.add_flow("Source", "Target", 50)
sankey.add_flow("Source", "Other", 30, label="30 units")
样式方法

所有方法都会返回 self,以便链式调用。

# Node colors
sankey.node_colors({
    'Income': '#2ecc71',
    'Expenses': '#e74c3c',
    'Savings': '#3498db'
})

# Use colormap for automatic colors
sankey.node_colors(colormap='Pastel1')

# Link colors (by source, target, or custom)
sankey.link_colors(by='source')  # Color by source node
sankey.link_colors(by='target')  # Color by target node
sankey.link_colors(opacity=0.6)  # Set link opacity

# Custom link colors
sankey.link_colors(colors={
    ('Income', 'Expenses'): '#ff6b6b',
    ('Income', 'Savings'): '#4ecdc4'
})

# Title
sankey.title("My Flow Diagram")
sankey.title("Budget Overview", font_size=20)

# Layout
sankey.layout(orientation='h')  # Horizontal (default)
sankey.layout(orientation='v')  # Vertical
sankey.layout(pad=20)  # Node padding
生成与导出
# Generate the diagram
sankey.generate()

# Save as interactive HTML
sankey.save_html("diagram.html")
sankey.save_html("diagram.html", auto_open=True)  # Open in browser

# Save as static image
sankey.save_image("diagram.png")
sankey.save_image("diagram.svg", format='svg')
sankey.save_image("diagram.png", width=1200, height=800)

# Get Plotly figure object for customization
fig = sankey.get_figure()
fig.update_layout(...)

# Show in notebook/browser
sankey.show()

数据格式

CSV 格式
source,target,value,label
Income,Housing,1500,Rent
Income,Food,600,Groceries
Income,Transport,400,Car
Income,Savings,500,Emergency Fund
Savings,Investments,300,Stocks
字典格式
data = {
    'source': ['Income', 'Income', 'Income', 'Expenses'],
    'target': ['Rent', 'Food', 'Savings', 'Tax'],
    'value': [1500, 600, 500, 400],
    'label': ['Housing', 'Groceries', 'Emergency', 'Federal']  # Optional
}
DataFrame 格式
import pandas as pd
df = pd.DataFrame({
    'from_node': ['A', 'A', 'B', 'C'],
    'to_node': ['B', 'C', 'D', 'D'],
    'flow_value': [100, 200, 150, 180]
})

配色方案

可用颜色映射
名称描述
Pastel1柔和的粉彩色
Pastel2柔和的粉彩色
Set1鲜明且彼此区分的颜色
Set2柔和且彼此区分的颜色
Set3明亮且彼此区分的颜色
Paired成对配色方案
viridis蓝-绿-黄
plasma紫-橙-黄
自定义颜色
# Hex colors
sankey.node_colors({
    'Category A': '#1abc9c',
    'Category B': '#3498db',
    'Category C': '#9b59b6'
})

# Named colors
sankey.node_colors({
    'Revenue': 'green',
    'Costs': 'red',
    'Profit': 'blue'
})

CLI 用法

# Basic usage
python sankey_creator.py --input flows.csv \
    --source from --target to --value amount \
    --output flow.html

# With title and colors
python sankey_creator.py --input budget.csv \
    --source category --target subcategory --value amount \
    --title "Budget Breakdown" \
    --colormap Pastel1 \
    --output budget.html

# PNG output
python sankey_creator.py --input data.csv \
    --source src --target dst --value val \
    --output diagram.png \
    --width 1200 --height 800
CLI 参数
参数描述默认值
--input输入 CSV 文件必填
--source源列名称必填
--target目标列名称必填
--value数值列名称必填
--output输出文件路径sankey.html
--title图表标题无
--colormap配色方案Pastel1
--link-opacity链接不透明度(0-1)0.5
--orientation'h' 或 'v'h
--width图像宽度(PNG/SVG)1000
--height图像高度(PNG/SVG)600

示例

预算流
sankey = SankeyCreator()
sankey.from_dict({
    'source': ['Salary', 'Salary', 'Salary', 'Salary', 'Savings', 'Investments'],
    'target': ['Housing', 'Food', 'Transport', 'Savings', 'Investments', 'Stocks'],
    'value': [2000, 800, 500, 1000, 700, 700]
})
sankey.title("Monthly Budget Flow")
sankey.node_colors({
    'Salary': '#27ae60',
    'Housing': '#e74c3c',
    'Food': '#f39c12',
    'Transport': '#3498db',
    'Savings': '#9b59b6',
    'Investments': '#1abc9c',
    'Stocks': '#34495e'
})
sankey.generate().save_html("budget_flow.html")
能源流
sankey = SankeyCreator()
sankey.add_flow("Coal", "Electricity", 100)
sankey.add_flow("Gas", "Electricity", 80)
sankey.add_flow("Solar", "Electricity", 30)
sankey.add_flow("Electricity", "Industry", 120)
sankey.add_flow("Electricity", "Residential", 60)
sankey.add_flow("Electricity", "Commercial", 30)

sankey.title("Energy Flow")
sankey.node_colors(colormap='Set2')
sankey.link_colors(by='source', opacity=0.4)
sankey.generate().save_html("energy.html")
用户旅程
sankey = SankeyCreator()
sankey.from_dict({
    'source': ['Landing', 'Landing', 'Product', 'Product', 'Cart', 'Cart'],
    'target': ['Product', 'Exit', 'Cart', 'Exit', 'Checkout', 'Exit'],
    'value': [1000, 200, 600, 200, 400, 100]
})
sankey.title("User Journey")
sankey.node_colors({
    'Landing': '#3498db',
    'Product': '#2ecc71',
    'Cart': '#f1c40f',
    'Checkout': '#27ae60',
    'Exit': '#e74c3c'
})
sankey.generate().save_html("journey.html")
多级流
# Three-level hierarchy
data = {
    'source': [
        # Level 1 -> Level 2
        'Revenue', 'Revenue', 'Revenue',
        # Level 2 -> Level 3
        'Products', 'Products', 'Services', 'Services'
    ],
    'target': [
        'Products', 'Services', 'Other',
        'Electronics', 'Software', 'Consulting', 'Support'
    ],
    'value': [500, 300, 50, 300, 200, 200, 100]
}

sankey = SankeyCreator()
sankey.from_dict(data)
sankey.title("Revenue Breakdown")
sankey.generate().save_html("revenue.html")

依赖项

plotly>=5.15.0
pandas>=2.0.0
kaleido>=0.2.0

限制

  • 导出静态图像(PNG/SVG)需要 kaleido 包
  • 包含大量节点的复杂图表可能难以阅读
  • 节点位置会自动计算(手动控制能力有限)
  • 链接颜色只能统一设置,或按源/目标设置

评论

支持 Markdown