You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ggsankey绘制收入到支出的ggplot桑基图并导出为png

使用ggsankey制作收入支出流向桑基图

前置依赖安装

首先安装并加载所需的R包:

# 首次使用需执行安装
install.packages(c("ggsankey", "ggplot2", "dplyr"))

# 加载依赖包
library(ggsankey)
library(ggplot2)
library(dplyr)

数据格式整理

我们需要将原始数据转换为桑基图要求的流向结构,构造「收入项→总资金汇总→支出项」的两级流向:

# 你的原始示例数据
data <- tibble::tribble(
                 ~Name, ~Annual.Amount,  ~Category,
    "Moira's Earnings",         50000L,   "Income",
   "Johnny's Earnings",        300000L,   "Income",
     "Living Expenses",        140000L, "Expenses",
       "Spent Savings",         25238L, "Expenses",
         "Liabilities",         44280L, "Expenses",
     "Planned Savings",         23000L, "Expenses",
               "Taxes",         98482L, "Expenses",
           "Insurance",         13000L, "Expenses"
  )

# 拆分收入、支出数据集
income_df <- filter(data, Category == "Income")
expense_df <- filter(data, Category == "Expenses")

# 构造第一级流向:各收入项到总资金节点
flow_income <- income_df %>% 
  mutate(
    source = Name,
    target = "总资金",
    value = Annual.Amount
  ) %>% 
  select(source, target, value)

# 构造第二级流向:总资金到各支出项
flow_expense <- expense_df %>% 
  mutate(
    source = "总资金",
    target = Name,
    value = Annual.Amount
  ) %>% 
  select(source, target, value)

# 合并流向数据并转换为ggsankey要求的长格式
full_flow <- bind_rows(flow_income, flow_expense)
sankey_long <- full_flow %>% make_long(source, target, value = value)

绘制桑基图并导出PNG

# 绘制桑基图
sankey_plot <- ggplot(sankey_long, 
       aes(x = x, next_x = next_x, node = node, next_node = next_node, 
           fill = factor(node), value = value)) +
  # 桑基流和节点设置
  geom_sankey(flow.alpha = 0.6, node.color = "#333333", smooth = 8) +
  # 节点标签设置,同时展示名称和金额
  geom_sankey_label(aes(label = paste0(node, "\n", value, "元")), 
                    size = 3.5, fill = "white", color = "#333333") +
  # 配色方案
  scale_fill_viridis_d(option = "plasma") +
  # 主题设置
  theme_sankey(base_size = 12) +
  labs(x = NULL, title = "年度收入支出流向") +
  theme(
    legend.position = "none",
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold")
  )

# 预览图片
print(sankey_plot)

# 导出为PNG格式,可自行调整尺寸、清晰度参数
ggsave("收入支出流向桑基图.png", plot = sankey_plot, width = 10, height = 7, dpi = 300)

样式调整说明

  • 修改geom_sankey的flow.alpha参数可调整流块透明度,smooth参数可调整流块的弯曲弧度
  • 替换scale_fill_viridis_d的参数可更换全局配色方案,也可使用scale_fill_manual自定义各节点颜色
  • 调整ggsave的width、height、dpi参数可修改导出图片的尺寸和清晰度

内容的提问来源于stack exchange,提问作者Ljupcho Naumov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:54:03