問題:
我有大量資料正在嘗試為我的用戶可視化。這可能是幾百個地塊。在當前的應用程式中,我正在使用 facet_wrap 制作 ggplot2 小倍數,并且在大約 100 個地塊中效果很好。但是,我希望用戶能夠匯出所有繪圖作為他們所做作業的記錄,并且能夠可視化所有繪圖,而不僅僅是前 100 個。我不太擔心它的格式(即作為 ggforce::facet_wrap_paginate() 或作為完全獨立的圖,如下所示)。
我嘗試了幾種在堆疊溢位中發現的方法,但似乎沒有任何效果
如果我嘗試匯出 R 中的圖,則以下代碼有效,但我無法以閃亮的方式下載作業。
library(shiny)
library(ggplot2)
ui <- fluidPage(
downloadButton("plot_download", "Download all plots"),
plotOutput("facet_plot")
)
server <- function(input, output) {
data <- reactive({
data.frame(group = rep(LETTERS, each = 100),
x = runif(n = 20, min = 10, max = 15),
y = runif(n = 20, min = 100, max = 150))
})
output$facet_plot <- renderPlot({
data() |>
ggplot(aes(x,y))
geom_point()
facet_wrap(vars(group))
})
output$plot_download <- downloadHandler(
filename = function() {
paste0(Sys.Date(), "_plot.pdf")
},
content = function(file) {
pdf(file)
data() |>
split(by="group") |>
lapply(function(data) {
gg <- data |>
ggplot(aes(x,y))
geom_point()
})
dev.off()
}
)
}
shinyApp(ui = ui, server = server)
uj5u.com熱心網友回復:
pdf您可以使用函式來代替呼叫ggsave函式。它將使用 、 、 和 等引數以所需width格式height保存dpi輸出units。您可以在此處找到檔案。
代碼將如下所示:
library(shiny)
library(ggplot2)
ui <- fluidPage(
downloadButton("plot_download", "Download all plots"),
plotOutput("facet_plot")
)
server <- function(input, output) {
data <- reactive({
data.frame(group = rep(LETTERS, each = 100),
x = runif(n = 20, min = 10, max = 15),
y = runif(n = 20, min = 100, max = 150))
})
output$facet_plot <- renderPlot({
data() %>%
ggplot(aes(x,y))
geom_point()
facet_wrap(vars(group))
})
output$plot_download <- downloadHandler(
filename = function() {
paste0(Sys.Date(), "_plot.pdf", sep = '')
},
content = function(file) {
ggsave(file, data() %>% ggplot(aes(x, y)) geom_point() facet_wrap(~group), dpi = 300)
}
)
}
shinyApp(ui = ui, server = server)
PS:我在您的代碼中到處更改了一些內容。保存繪圖的代碼應該與您之前的代碼一起使用。
編輯
為了根據您的需要擴展解決方案,我對代碼進行了一些更改。有一個包叫ggforce. 你可以在這里找到它。它將幫助您將圖表保存facet_wrap為單個頁面上的單獨圖表或以行和列方式保存。
代碼如下所示:
filename = function() {
paste0(Sys.Date(), "_plot.pdf", sep = '')
},
content = function(file) {
pdf(file)
#ggsave(file, data() %>% ggplot(aes(x, y)) geom_point() facet_wrap(~group), dpi = 300)
for(i in 1:length(unique(data()$group))) {
print(data() %>% ggplot(aes(x, y)) geom_point()
facet_wrap_paginate(~group, ncol = 1, nrow = 1, page = i))
}
dev.off()
}
請注意,我根據您的示例資料使用組。您可以根據需要進行更改。facet_wrap_paginate是您在這里需要的功能。您可以使用它指定要在每頁上保存的圖表的列數和行數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416814.html
標籤:
