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

已生成含ggplotly的HTML,如何从R脚本插入图像(对象/文件)

解决方案:在包含ggplotly图形的HTML中插入图像

方法一:插入ggplot对象p到HTML中

你可以将静态ggplot对象转换为HTML兼容元素,或者转成交互式plotly对象后加入页面,两种方式任选:

方式1:转为交互式plotly对象

将p通过ggplotly()转换为交互式图形,和原有的l1、l2一起放入tagList后保存:

library(ggplot2)
library(plotly)
library(htmltools)
library(terra)
library(magrittr)
library(imager)

# 生成原有交互式图形
g1 <- ggplot(data=data.frame(x=1:10, y=1:10)) +
  geom_point(aes(x=x, y=y))
g2 <- ggplot(data=data.frame(x=11:20, y=1:10)) +
  geom_point(aes(x=x, y=y))
l1 <- ggplotly(g1)
l2 <- ggplotly(g2)

# 生成ggplot对象p
foto <- imresize(load.image(system.file("ex/logo.tif", package="terra")),0.25)
fotodf <- as.data.frame(foto,wide="c") %>% mutate(rgb.val=rgb(c.1,c.2,c.3))
p <- ggplot(fotodf,aes(x,y))+geom_raster(aes(fill=rgb.val)) + scale_fill_identity() +
  scale_y_reverse() + coord_fixed() + theme_void()

# 将p转为plotly对象并保存
lp <- ggplotly(p)
htmltools::save_html(htmltools::tagList(l1, l2, lp), file = "index.html")

方式2:转为静态HTML元素

如果不需要交互式效果,可将p转为grob对象再转成HTML标签:

library(grid)

# 生成p的代码同上...

# 转换为HTML兼容元素
p_grob <- ggplotGrob(p)
p_tag <- htmltools::as.tags(p_grob)

# 保存到HTML
htmltools::save_html(htmltools::tagList(l1, l2, p_tag), file = "index.html")

方法二:直接插入logo.tif图片文件

由于浏览器不支持直接显示TIFF格式,需要先将其转换为PNG/JPEG等Web兼容格式,再用HTML的img标签插入:

library(terra)
library(htmltools)

# 生成原有交互式图形的代码同上...

# 将TIFF转为PNG
logo_tif_path <- system.file("ex/logo.tif", package="terra")
logo_png_path <- "logo.png" # 保存到当前工作目录
terra::writeRaster(terra::rast(logo_tif_path), logo_png_path, overwrite = TRUE)

# 创建img标签,可自定义宽度、替代文本
img_tag <- htmltools::img(src = logo_png_path, alt = "Terra Logo", width = "200px")

# 保存到HTML
htmltools::save_html(htmltools::tagList(l1, l2, img_tag), file = "index.html")

注意事项

  • 确保转换后的图片文件(如logo.png)和index.html在同一目录下,否则需要填写完整路径。
  • 若需要调整元素排列顺序,直接修改tagList中的元素顺序即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:47:33