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

如何将Shiny中echarts4r绘制的图表保存为SVG或PNG文件

实现Shiny中echarts4r图表的SVG/PNG本地保存方案

以下是在你提供的Shiny应用基础上,添加图表保存功能的完整代码:

UI部分

library(shiny)
library(echarts4r)
library(base64enc)

ui <- fluidPage(
  # 新增保存按钮
  downloadButton("save_svg", "保存为SVG"),
  downloadButton("save_png", "保存为PNG"),
  actionButton("add", "Add Data to y"),
  echarts4rOutput("plot"),
  verbatimTextOutput("selected"),
  
  # 自定义JavaScript代码,用于获取ECharts图表数据
  tags$script(HTML('
    // 获取ECharts实例
    function getEchartsInstance(id) {
      return echarts.getInstanceByDom(document.getElementById(id));
    }
    
    // 响应SVG保存请求
    Shiny.addCustomMessageHandler("save_svg", function(message) {
      var chart = getEchartsInstance("plot");
      var svgContent = chart.getSVG();
      Shiny.setInputValue("svg_data", svgContent);
    });
    
    // 响应PNG保存请求
    Shiny.addCustomMessageHandler("save_png", function(message) {
      var chart = getEchartsInstance("plot");
      chart.getDataURL({
        type: "png",
        pixelRatio: 2, // 提升图片分辨率
        callback: function(dataUrl) {
          var pngBase64 = dataUrl.replace("data:image/png;base64,", "");
          Shiny.setInputValue("png_data", pngBase64);
        }
      });
    });
  '))
)

Server部分

server <- function(input, output, session){

  data <- data.frame(x = rnorm(10, 5, 3), y = rnorm(10, 50, 12), z = rnorm(10, 50, 5))
  
  react <- eventReactive(input$add, {
    set.seed(sample(1:1000, 1))
    data.frame(x = rnorm(10, 5, 2), y = rnorm(10, 50, 10))
  })
  
  output$plot <- renderEcharts4r({
    data |>
     e_charts(x) |>
     e_scatter(y) |>
     e_scatter(z) |>
     e_brush(throttleDelay = 1000) |>
     e_toolbox_feature(feature = "saveAsImage") # 可选:在图表工具栏添加官方导出按钮
  })
  
  observeEvent(input$add, {
    echarts4rProxy("plot") |>
      e_append1_p(0, react(), x, y)
  })
  
  output$selected <- renderPrint({
    input$plot_brush
  })
  
  # SVG下载逻辑
  output$save_svg <- downloadHandler(
    filename = function() {
      paste0("echarts_plot_", Sys.Date(), ".svg")
    },
    content = function(file) {
      session$sendCustomMessage("save_svg", list())
      req(input$svg_data)
      writeLines(input$svg_data, file)
    }
  )
  
  # PNG下载逻辑
  output$save_png <- downloadHandler(
    filename = function() {
      paste0("echarts_plot_", Sys.Date(), ".png")
    },
    content = function(file) {
      session$sendCustomMessage("save_png", list())
      req(input$png_data)
      base64decode(input$png_data, file)
    }
  )
  
}

shinyApp(ui, server)

关键实现说明

  • 借助ECharts原生API:使用getSVG()直接获取矢量SVG内容,用getDataURL()获取PNG的base64编码数据
  • Shiny消息交互:通过sendCustomMessage触发前端JS执行,再用setInputValue将图表数据传递到服务器端
  • 下载处理:利用downloadHandler将接收到的SVG/PNG数据写入本地文件,自动触发浏览器下载
  • 可选增强:添加e_toolbox_feature(feature = "saveAsImage")后,图表右上角会出现官方导出按钮,提供额外保存入口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:55:18