0

I have an R shiny which generates a dashboard with some plots.

I implemented a download button to download the report as a PDF using knitr. Here is part the problematic part of the code:

hist_pl <- reactive({
  inFile <- input$file
  if (is.null(inFile))
    return(NULL)


      dataf <- getDF()
      h <- hist(dataf)
      par(new = T)


      plot(x = h$mids, y=ec(h$mids)*max(h$counts), col = rgb(0,0,0,alpha=0), axes=F,xlab=NA, ylab=NA)

    }) 

  output$hist1 <- renderPlot({
    hist_pl()
  })

The problem is as follow:

When I comment the 'renderPlot' part of the code, the histogram appears normally in the PDF report (but not in the dashboard). When I uncomment it, the histogram disappear from the PDF (and appear in the dashboard).

The code for the download button is fairly simple:

  output$report = downloadHandler(
    filename = 'myreport.pdf',
    content = function(file) {
      out = knit2pdf('input.Rnw', clean = TRUE)
      file.rename(out, file) # move pdf to file for downloading
    },
    contentType = 'application/pdf'

  )

and the input.Rnw file:

\documentclass{article}

    \begin{document}

    <<names>>=
    input$Val1
    input$Val2
    @

    <<>>=
    #output$mpgPlot ## N.B. This threw an error! Cannot call an object like this from shiny
    print(hist_pl())
    @

    <<>>=
    print(hist_pl())
    @

\end{document}

Can someone tell me what could the problem be?

ifreak
  • 1,726
  • 4
  • 27
  • 45
  • Your title says "ggplot" but your code says base "plot". – Gregor Thomas Oct 13 '17 at 13:45
  • @Gregor sorry, corrected it. But the problem is actually appearing in both cases – ifreak Oct 13 '17 at 13:46
  • Base plots aren't objects, they can't be assigned, printed, and passed around. You're trying to handle a base plot like it's a ggplot. That doesn't work. – Gregor Thomas Oct 13 '17 at 13:48
  • so is there a way to solve this? – ifreak Oct 13 '17 at 13:51
  • Use ggplot's `geom_histogram()` instead? – David Klotz Oct 13 '17 at 14:00
  • @DavidKlotz there is some functionalities that I would like to include in my histogram that ggplot does not support (e.g., ecdf curve) – ifreak Oct 13 '17 at 14:03
  • There are plenty of examples of shiny apps using base plots. [here's one](https://shiny.rstudio.com/gallery/faithful.html), [here's another](https://shiny.rstudio.com/gallery/telephones-by-region.html). These are nice simple apps, should be easy to follow. Or use `ggplot`, [here's an example of ECDF curves in ggplot](https://stackoverflow.com/q/6989015/903061). – Gregor Thomas Oct 13 '17 at 14:06
  • @Gregor The examples you provided do not have the generate report functionality. My shiny app is working fine, the problem only appear when trying to generate a PDF. Besides, ECDF in ggplot2 looks fine in the case where no bars are shown in the plot. In my case, I need to show the bars and ECDF curve, which is as I read problematic in ggplot – ifreak Oct 13 '17 at 14:10

0 Answers0