![](/img/trans.png)
[英]R plotly + shiny reactive coupled event - Refresh chart with argument from click on same chart
[英]Extract all click event plots from Shiny, Plotly - R
在下面的shiny
应用程序中, plotly
包用于创建交互式相关热图。 单击单个图块时,将显示相应的散点图。 然后,可以通过单击download plot as png
来download plot as png
单个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)
您可以使用webshot
使用webshot
说明捕获Plotly的HTML输出的静态图像: https ://plot.ly/r/static-image-export/
下面循环的示例生成来自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)
}
但是,如果您可能会执行此操作数十次,则执行以下步骤所需的计算量确实会增加。
R
生成JSON plotly
对象 htmlwidgets
/ htmltools
生成一个自包含的HTML网页 webshot
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.