GGPlotly:downloadHandler 给出空图

GGPlotly: downloadHandler giving empty plot

我在使用 plotly 时遇到了一些困难。我希望能够以 pdf 格式下载 plotly。然而,在我的代码中添加一些 x 和 y 轴参数时(因为如果我将 ggplot 转移到 plotly,x 和 y 轴的标题被剪切)

此代码正在下载 pdf 文件:

library(shiny)
library(DT)
library(ggplot2)
library(plotly)


shinyApp(
  ui = fluidPage(
    fluidRow(downloadButton('downloadplot',label='Download Plot')),
    plotlyOutput('plot1')
  ),
  server = function(input, output) {

    testplot <- function(){

a <- ggplot(mtcars, aes(x = interaction(cyl, carb, lex.order = T), y = mpg,fill = interaction(cyl, carb, lex.order = T))) + 
  geom_boxplot()

    }

    output$plot1 <- renderPlotly({testplot()})

    output$downloadplot <- downloadHandler(
      filename ="plot.pdf",
      content = function(file) {
        pdf(file, width=12, height=6.3)
        print(testplot())
        dev.off()
      })})

并添加此代码来修复 ggplotly 的标题失败:

a <- ggplot(mtcars, aes(x = interaction(cyl, carb, lex.order = T), y = mpg,fill = interaction(cyl, carb, lex.order = T))) + 
  geom_boxplot()

p <- ggplotly(a + ylab(" ") + xlab(" ")) 
x <- list(
  title = "[x]"
)
y <- list(
  title = "[y]"
)
p %>% layout(xaxis = x, yaxis = y)}

给出一个空图...

感谢您的帮助!

我的问题已经解决了。该解决方案并不优雅,但它有效!

所以诀窍是在 renderPlotly 而不是 testplot() 函数中设置 x 和 y 标题。

然而,x 和 y 轴标题必须在 testplot() 函数中额外输入 - 因为这将是我们的 pdf 输出,并且绘图视图是使用 plotly 完成的。

代码如下:

library(shiny)
library(DT)
library(ggplot2)
library(plotly)


shinyApp(
  ui = fluidPage(
    fluidRow(downloadButton('downloadplot',label='Download Plot')),
    plotlyOutput('plot1')
  ),
  server = function(input, output) {

    testplot <- function(){

      a <- ggplot(mtcars, aes(x = interaction(cyl, carb, lex.order = T), y = mpg,fill = interaction(cyl, carb, lex.order = T))) + 
        geom_boxplot()

    }

    output$plot1 <- renderPlotly({

      p <- ggplotly(testplot() + ylab(" ") + xlab(" ")) 
      x <- list(
        title = "[x]"
      )
      y <- list(
        title = "[y]"
      )
      p %>% layout(xaxis = x, yaxis = y)})

    output$downloadplot <- downloadHandler(
      filename ="plot.pdf",
      content = function(file) {
        pdf(file, width=12, height=6.3)
        print(testplot())
        dev.off()
      })})