GGPlotly:downloadHandler给出空图

时间:2016-04-25 07:31:50

标签: r ggplot2 plotly

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)}

给出一个空图......

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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

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

然而,必须在testplot()函数中另外输入x和y轴标题 - 因为这将是我们的输出为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()
      })})