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

如何修改Sankey图字体为加粗Arial并导出为PDF?

解决方案

一、修改为加粗Arial字体

要统一设置Sankey图的所有文本(标题、节点标签、注释)为加粗Arial字体,可通过layout()配置全局字体,同时单独指定注释的字体参数:

library(sfo)
library(dplyr, warn = FALSE)
library(plotly)

# 数据处理与生成初始Sankey图
sfo_passengers %>% 
  filter(operating_airline == "United Airlines",
         activity_period >= 201901 & activity_period < 202001) %>%
  mutate(terminal = ifelse(terminal == "International", "international", terminal)) %>%
  group_by(operating_airline,activity_type_code, geo_summary, geo_region,  terminal) %>%
  summarise(total = sum(passenger_count), .groups = "drop") %>%
  sankey_ly(cat_cols = c("operating_airline", "terminal","geo_summary", "geo_region", "activity_type_code"), 
            num_col = "total",
            title = "Dist. of United Airlines Passengers at SFO During 2019")

p <- plotly::last_plot()

# 添加注释并配置字体,同时调整全局布局字体
p <- p %>%
  add_annotations(
    text = c("Terminals", "Domestic/Int"), 
    x = c(0.2, 0.5), 
    y = c(1, 1), 
    showarrow = FALSE,
    font = list(family = "Arial", size = 12, color = "black", weight = "bold")
  ) %>%
  layout(
    font = list(family = "Arial", weight = "bold"),
    title = list(font = list(family = "Arial", weight = "bold"))
  )

# 预览修改后的图表
p
  • layout(font = list(...))会统一设置图表内所有默认文本的字体样式
  • 注释文本需要单独在add_annotations()的font参数中定义,避免样式继承问题
  • 标题单独配置字体是为了确保加粗效果优先级更高

二、导出为PDF格式

Plotly图表导出PDF有两种实用方法:

方法1:使用Orca工具(官方推荐)

需先安装Orca跨平台导出工具,再调用plotly::export():

# 导出PDF文件
plotly::export(p, file = "sankey_united_2019.pdf")

方法2:HTML转PDF(无需额外安装Orca)

借助htmlwidgets将图表保存为HTML,再通过系统的pandoc转为PDF(多数RStudio环境默认自带pandoc):

library(htmlwidgets)

# 保存为独立HTML文件
saveWidget(p, file = "sankey_united_2019.html", selfcontained = TRUE)

# 调用pandoc转换为PDF
system("pandoc -s sankey_united_2019.html -o sankey_united_2019.pdf")
  • 方法1导出效果更稳定,适合复杂交互式图表
  • 方法2无需额外安装工具,操作更轻量化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:15:28