从Shiny,Plotly-R中提取所有点击事件图

J.C*_*Con 5 r shiny plotly r-plotly

在以下shiny应用程序中,该plotly程序包用于创建交互式关联热图.单击单个图块时,将显示相应的散点图.然后,可以通过单击下载单个散点图download plot as png.但有没有办法一次下载所有可能的散点图而不必点击每个单独的瓷砖并保存每个单独的瓷砖?谢谢

library(plotly)
library(shiny)

# compute a correlation matrix
correlation <- round(cor(mtcars), 3)
nms <- names(mtcars)

ui <- fluidPage(
  mainPanel(
    plotlyOutput("heat"),
    plotlyOutput("scatterplot")
  ),
  verbatimTextOutput("selection")
)

server <- function(input, output, session) {
  output$heat <- renderPlotly({
    plot_ly(x = nms, y = nms, z = correlation, 
            key = correlation, type = "heatmap", source = "heatplot") %>%
      layout(xaxis = list(title = ""), 
             yaxis = list(title = ""))
  })

  output$selection <- renderPrint({
    s <- event_data("plotly_click")
    if (length(s) == 0) {
      "Click on a cell in the heatmap to display a scatterplot"
    } else {
      cat("You selected: \n\n")
      as.list(s)
    }
  })

  output$scatterplot <- renderPlotly({
    s <- event_data("plotly_click", source = "heatplot")
    if (length(s)) {
      vars <- c(s[["x"]], s[["y"]])
      d <- setNames(mtcars[vars], c("x", "y"))
      yhat <- fitted(lm(y ~ x, data = d))
      plot_ly(d, x = ~x) %>%
        add_markers(y = ~y) %>%
        add_lines(y = ~yhat) %>%
        layout(xaxis = list(title = s[["x"]]), 
               yaxis = list(title = s[["y"]]), 
               showlegend = FALSE)
    } else {
      plotly_empty()
    }
  })

}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

Mat*_*ill 4

您可以webshot使用此处的说明捕获 Plotly HTML 输出的静态图像: https: //plot.ly/r/static-image-export/

下面的 for 循环示例从 生成随机散点图mtcars

library(plotly)
library(webshot)

## You'll need to run the function the first time if you dont't have phantomjs installed
#webshot::install_phantomjs()
ColumnOptions <- colnames(mtcars)

for (i in seq_len(5)){
  xCol <- sample(ColumnOptions,1)
  yCol <- sample(ColumnOptions,1)
  ThisFileName <- paste0("Scatter_",xCol,"_vs_",yCol,".png")

  plot_ly(x = mtcars[[xCol]], y = mtcars[[yCol]], type = "scatter", mode = "markers") %>% 
    export(., file = ThisFileName)
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您可能要执行此操作数十次,则执行以下步骤所需的计算量确实会增加。

  1. 生成 JSONplotly对象R
  2. 使用htmlwidgets/htmltools生成独立的 HTML 网页
  3. 将 HTML 呈现为浏览器可以通过外部程序看到它 -webshot
  4. 用于webshot渲染该 HTML 的图像并将其另存为 PNG

这实际上并不是plotly慢的反映,但打个比方,这有点像使用飞机旅行半英里——飞机会带你到达那里,但如果你需要多次旅行你也许应该考虑一辆车。

上面的循环plotly需要 27 秒来渲染 5 个 PNG 图像,但下面使用的替代方法ggplot2需要 1.2 秒。

library(ggplot2)

ColumnOptions <- colnames(mtcars)

for (i in seq_len(5)){
  xCol <- sample(ColumnOptions,1)
  yCol <- sample(ColumnOptions,1)
  ThisFileName <- paste0("ggplot2_Scatter_",xCol,"_vs_",yCol,".png")

  ggplot() + 
    geom_point(aes(x = mtcars[[xCol]], y = mtcars[[yCol]])) +
    labs(x = xCol, y = yCol) -> ThisPlot 

  ggsave(plot = ThisPlot, filename = ThisFileName)
}
Run Code Online (Sandbox Code Playgroud)