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

如何在邮件中正确嵌入gt表格与ggplot图像?

解决blastula邮件中嵌入gt表格与ggplot图像的表头混乱问题

尝试向团队发送的邮件中同时嵌入gt表格与多个ggplot图像。使用as_raw_html()将gt表格转换为HTML格式嵌入邮件时,列表头显示混乱;不转换则仅能显示表格内容,无表格结构。

问题原因

gt::as_raw_html()会生成包含完整HTML文档结构(包括<head>中的全局样式声明)的代码,直接插入邮件markdown正文时,这些全局样式会与邮件客户端的默认样式冲突,导致表头显示异常;而直接使用未转换的gt对象,markdown无法解析其表格结构,只能输出纯文本内容。

解决思路

  1. 正确转换GT表格:使用gt::as_html(inline_css = TRUE)生成内联CSS的表格HTML,将样式直接写入表格元素中,避免全局样式冲突,确保邮件客户端正确渲染表格结构和样式。
  2. 组件式构建邮件:利用blastula的链式调用方法,分别添加markdown文本、gt表格、ggplot图像,避免多次嵌套解析导致的问题,提升代码可读性。

修改后的完整代码

library(purrr)
library(ggplot2)
library(gt)
library(glue)
library(blastula)
library(dplyr)
library(cowplot)

generate_plots <- function(species) {
  
  subset_data <- iris %>% 
    filter(Species == species)
  
  bar_plot <- ggplot(subset_data, aes(x = Sepal.Length)) + 
    geom_bar(stat = "count") +
    theme_minimal() +
    ggtitle(glue("{species} - Sepal Length Count"))
  
  scatter_plot <- ggplot(subset_data, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point() +
    theme_minimal() +
    ggtitle(glue("{species} - Sepal Length vs Width"))
  
  box_plot <- ggplot(subset_data, aes(y = Sepal.Length)) +
    geom_boxplot() +
    theme_minimal() +
    ggtitle(glue("{species} - Sepal Length Distribution"))
  
  combined_charts <- cowplot::plot_grid(bar_plot, scatter_plot, box_plot, 
                                        axis = "l", ncol = 1, align = "v", 
                                        rel_heights = c(5,5,5))

  # 返回ggplot对象,后续通过blastula添加到邮件
  combined_charts
    
}

plots <- map(unique(iris$Species), generate_plots)

# 创建GT表格并生成内联样式的HTML
summary_table <- gt(iris) %>% 
  as_html(inline_css = TRUE)

# 构建邮件正文
formatted_email <- compose_email(
  body = md("
Team,

Check these out....
")
) %>%
  # 添加GT表格
  body_add_html(summary_table) %>%
  # 遍历添加每个物种的组合图表及标题
  pwalk(list(plots, unique(iris$Species)), function(plot, sp) {
    . %>%
      body_add(md(glue("\n\n### {sp} 分析图表"))) %>%
      body_add_ggplot(plot, width = 7, height = 10)
  }) %>%
  # 添加签名
  body_add(md("\n\nThanks,\n\nMyName"))

# 预览邮件
formatted_email

修改说明

  • GT表格处理:替换as_raw_html()为as_html(inline_css = TRUE),生成内联样式的表格HTML,确保邮件客户端能正确渲染表头和表格样式。
  • 图像添加优化:修改generate_plots返回ggplot对象,通过body_add_ggplot()逐个添加到邮件中,并增加物种标题,提升邮件内容的可读性。
  • 邮件结构优化:使用blastula的链式调用,依次添加文本、表格、图像和签名,代码结构更清晰,避免嵌套解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:33:09