在运行以下可再现代码时,用户可以通过单击渲染的shiny 屏幕顶部的单选按钮(按编码,默认为数据), Select 查看实际数据或数据的绘图.在渲染屏幕的底部,您将看到一个"复制"按钮.通过 Select "Data"(数据)然后 Select "Copy"(复制),您可以轻松地将数据粘贴到XLS中.

但是,如果用户 Select 查看绘图,我希望用户也能够以相同的方式复制/粘贴绘图.如何做到这一点?

我try 在下面的observeEvent(...)中的capture.output(...)函数(及其各种迭代)中插入plotPNG(...),使用条件if input$view == 'Plot'触发的条件,但还没有成功.

library(shiny)
library(ggplot2)

ui <- fluidPage(
   radioButtons("view",
                label = "View data or plot",
                choiceNames = c('Data','Plot'),
                choiceValues = c('Data','Plot'),
                selected = 'Data',
                inline = TRUE
                ),
   conditionalPanel("input.view == 'Data'",tableOutput("DF")),
   conditionalPanel("input.view == 'Plot'",plotOutput("plotDF")),
   actionButton("copy","Copy",style = "width:20%;")
)
  
server <- function(input, output, session) {
  
  data <- data.frame(Period = c(1,2,3,4,5,6),Value = c(10,20,15,40,35,30))

  output$DF <- renderTable(data)
  output$plotDF <- renderPlot(ggplot(data, aes(Period,Value)) + geom_line())

  observeEvent(
    req(input$copy),
    writeLines(
      capture.output(
        write.table(
          x = data,
          sep = "\t",
          row.names = FALSE
          )
        ),
      "clipboard")
    )
 
}

shinyApp(ui, server)

推荐答案

边缘测试.

library(shiny)
library(ggplot2)

js <- '
async function getImageBlobFromUrl(url) {
  const fetchedImageData = await fetch(url);
  const blob = await fetchedImageData.blob();
  return blob;
}
$(document).ready(function () {
  $("#copybtn").on("click", async () => {
    const src = $("#plotDF>img").attr("src");
    try {
      const blob = await getImageBlobFromUrl(src);
      await navigator.clipboard.write([
        new ClipboardItem({
          [blob.type]: blob
        })
      ]);
      alert("Image copied to clipboard!");
    } catch (err) {
      console.error(err.name, err.message);
      alert("There was an error while copying image to clipboard :/");
    }
  });
});
'

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),
  br(),
  actionButton("copybtn", "Copy", icon = icon("copy"), class = "btn-primary"),
  br(),
  plotOutput("plotDF")
)

server <- function(input, output, session){
  
  output[["plotDF"]] <- renderPlot({
    ggplot(
      iris, aes(x = Sepal.Length, y = Sepal.Width)
    ) + geom_point()
  })
  
}

shinyApp(ui, server)

enter image description here


EDIT

alert 不好.我建议改为shinyToastify英镑.

library(shiny)
library(shinyToastify)
library(ggplot2)

js <- '
async function getImageBlobFromUrl(url) {
  const fetchedImageData = await fetch(url);
  const blob = await fetchedImageData.blob();
  return blob;
}
$(document).ready(function () {
  $("#copybtn").on("click", async () => {
    const src = $("#plotDF>img").attr("src");
    try {
      const blob = await getImageBlobFromUrl(src);
      await navigator.clipboard.write([
        new ClipboardItem({
          [blob.type]: blob
        })
      ]);
      Shiny.setInputValue("success", true, {priority: "event"});
    } catch (err) {
      console.error(err.name, err.message);
      Shiny.setInputValue("failure", true, {priority: "event"});
    }
  });
});
'

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),
  useShinyToastify(),
  br(),
  actionButton("copybtn", "Copy", icon = icon("copy"), class = "btn-primary"),
  br(),
  plotOutput("plotDF")
)

server <- function(input, output, session){
  
  output[["plotDF"]] <- renderPlot({
    ggplot(
      iris, aes(x = Sepal.Length, y = Sepal.Width)
    ) + geom_point()
  })
  
  observeEvent(input[["success"]], {
    showToast(
      session,
      input,
      text = tags$span(
        style = "color: white; font-size: 20px;", "Image copied!"
      ),
      type = "success",
      position = "top-center",
      autoClose = 3000,
      pauseOnFocusLoss = FALSE,
      draggable = FALSE,
      style = list(
        border = "4px solid crimson",
        boxShadow = "rgba(0, 0, 0, 0.56) 0px 22px 30px 4px"
      )
    )
  })

  observeEvent(input[["failure"]], {
    showToast(
      session,
      input,
      text = tags$span(
        style = "color: white; font-size: 20px;", "Failed to copy image!"
      ),
      type = "error",
      position = "top-center",
      autoClose = 3000,
      pauseOnFocusLoss = FALSE,
      draggable = FALSE,
      style = list(
        border = "4px solid crimson",
        boxShadow = "rgba(0, 0, 0, 0.56) 0px 22px 30px 4px"
      )
    )
  })
  
}

shinyApp(ui, server)

enter image description here

R相关问答推荐

R根据名称的载体对收件箱列采取行动

使用map()内的公式()创建多个公式

使用facet_wrap()时如何将面板标题转换为脚注?

从API中抓取R数据SON

对lme 4对象运行summary()时出错(diag中的错误(from,names = RST):对象unpackedMatrix_diag_get找不到)

根据R中的另一个日期从多列中 Select 最近的日期和相应的结果

使用tidyverse方法绑定行并从一组管道列表执行左连接

为什么观察不会被无功值变化触发?

用值序列对行进行子集化,并标识序列开始的列

非线性混合效应模型(NLME)预测变量的置信区间

在ggplot2中更改小提琴情节的顺序

如何从R ggplot图片中获取SVG字符串?

R Read.table函数无法对制表符分隔的数据正常工作

R Select()可以测试不存在的子集列

如何在PDF格式的kableExtra表格中显示管道字符?

如何将一些单元格的内容随机 Select 到一个数据框中?

为什么我对圆周率图的蒙特卡罗估计是空的?

如何将这个小列表转换为数据帧?

如何删除设置大小的曲线图并添加条形图顶部数字的百分比

计算来自单独分组的分幅的值的百分位数