【问题标题】:GGPlotly: downloadHandler giving empty plotGGplotly:downloadHandler 给出空图
【发布时间】:2016-04-25 07:31:50
【问题描述】:

我在使用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)}

给出一个空的情节...

感谢您的帮助!

【问题讨论】:

  • 但是我应该在哪里使用return(a)..而不是我需要使用downloadHandler的if语句
  • 如果你有情节用户名等,你可以使用plotly_IMAGE。或者您需要使用不同的功能,一种用于绘图,另一种用于 pdf ggplot
  • 我没有用户名。 plotly 的问题是我不能在 Internet Explorer 中使用 plotly download image button,这就是为什么唯一的解决方案是添加 downlaodHandler 这会给我 pdf 文件
  • 您是否尝试创建不同的功能 - 一个带有 plotly 和一个带有 ggplot(仅适用于 pdf)?

标签: r ggplot2 plotly


【解决方案1】:

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

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

但是 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()
      })})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多