2

When I insert an embedded shiny app to my document like showed on Embedded Shiny Apps, with “runtime: shiny” in the YAML and click the button “Run Document” there are only image placeholder icons.

But when I remove the shiny app and also remove the “runtime: shiny” from the YAML the embedded image is visible after rendering.

The following to links have the topic of embedding images but none solves my issue – in both cases the image placeholder icon remains.

Question:

  • What should I change in my code to get the images?
  • Or has it something to do with my initial choice of encoding?

Below my code example with an embedded shiny app – so when necessary you just need to copy and paste. The shiny app is just a copy from the r studio gallery…

EDIT: As suggested by timfaber I added the renderImage() parts in the code. But two question concering the rendering still remain.

How can I suppress the need for scroll up or down to see the entire image? and How can I position an image in an shiny app?

---
title: "Documentation"
author: "tueftla"
date: "23 Mai 2017"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(shiny)
```

Here is my documentation …  
and also one of the images.  


# my old version
#![](image1.png)
# 
```{r, echo=FALSE}
    # Here you have to scroll up or down to see the entire image
    shinyApp(

         ui = fluidPage(
                imageOutput("image1")
         ),

         server = function(input, output) {
                 output$image1=renderImage({
         # the images are stored in a subdirectory named images
         filename <- normalizePath(file.path('./images',
                              paste('image1', '.png', sep='')))

         # Return a list containing the filename
         list(src = filename, height = 600,width=800)
         }, deleteFile = FALSE)

         }


     )

```

In the second code sequence I want to position the image at the right. See the comment "old version"

```{r, echo = FALSE}

shinyApp(

  ui = fluidPage(

    # Application title
    titlePanel("Tabsets"),

    # my old version
    #img(src=image2.png', align = "right"),
    # my new version with bad alignment - note also the change in server
    imageOutput("image2", height = 200,width=100),


    # Sidebar with controls to select the random distribution type
    # and number of observations to generate. Note the use of the
    # br() element to introduce extra vertical spacing
    sidebarLayout(
      sidebarPanel(
        radioButtons("dist", "Distribution type:",
                     c("Normal" = "norm",
                       "Uniform" = "unif",
                       "Log-normal" = "lnorm",
                       "Exponential" = "exp")),
        br(),

        sliderInput("n", 
                    "Number of observations:", 
                     value = 500,
                     min = 1, 
                     max = 1000)
      ),

      # Show a tabset that includes a plot, summary, and table view
      # of the generated distribution
      mainPanel(
        tabsetPanel(type = "tabs", 
          tabPanel("Plot", plotOutput("plot")), 
          tabPanel("Summary", verbatimTextOutput("summary")), 
          tabPanel("Table", tableOutput("table"))
        )
      )
    )
  ),

  server = function(input, output) {

      # the image rendering - necessary for the image in ui of this app
      output$image2=renderImage({
      # the images are stored in a subdirectory named images
      filename <- normalizePath(file.path('./images',
                                paste('image2', '.png', sep='')))

      # Return a list containing the filename
      list(src = filename, height = 200,width=100)
      }, deleteFile = FALSE)

      # Reactive expression to generate the requested distribution.
      # This is called whenever the inputs change. The output
      # functions defined below then all use the value computed from
      # this expression
      data <- reactive({
        dist <- switch(input$dist,
                       norm = rnorm,
                       unif = runif,
                       lnorm = rlnorm,
                       exp = rexp,
                       rnorm)

        dist(input$n)
      })

      # Generate a plot of the data. Also uses the inputs to build
      # the plot label. Note that the dependencies on both the inputs
      # and the data reactive expression are both tracked, and
      # all expressions are called in the sequence implied by the
      # dependency graph
      output$plot <- renderPlot({
        dist <- input$dist
        n <- input$n

        hist(data(), 
             main=paste('r', dist, '(', n, ')', sep=''))
      })

      # Generate a summary of the data
      output$summary <- renderPrint({
        summary(data())
      })

      # Generate an HTML table view of the data
      output$table <- renderTable({
        data.frame(x=data())
      })

  },


)
```

I hope I gave enough information... but when something is missing please comment. I will edit my question.

Many thanks in advance!

Second Edit: The following is showing my folder structure and the result.Folder structure and result

tueftla
  • 369
  • 1
  • 3
  • 16
  • Not sure but you don't have to define the shinyapp inside Markdown, you can directly call server/ui elements as renderPlot() etc. See http://rmarkdown.rstudio.com/authoring_shiny.html – timfaber May 30 '17 at 08:41
  • @timfaber: Thanks for your hint just using `renderPlot()`. But the issue with the placeholder icon for the image remains… – tueftla May 30 '17 at 09:18
  • You have to use the shiny function `renderImage()`. See pre-rendered images at http://shiny.rstudio.com/articles/images.html But now a new problem with the right alignment of the images occurs... – tueftla May 30 '17 at 11:01
  • can you update your code with your `renderImage()` part? – timfaber May 30 '17 at 11:09
  • @timfaber: I have updated my code. And see the new two questions - perhaps you have an idea how to solve this issue. I am trying something with `fillPage()` and `fillRow()` to suppress the need for scrolling... – tueftla May 30 '17 at 14:01

1 Answers1

1

I think it can be done a lot easier. For me the problem was defining the right path for the image. No need to use renderImage! Scaling the image resolves the scrolling and using img allows you to define the position (alignment):

---
title: "Documentation"
author: "tueftla"
date: "23 Mai 2017"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(shiny)
```

Here is my documentation …  
and also one of the images.  


```{r, echo = FALSE}

fluidPage(

titlePanel("Tabsets"),

img(src='www/logotitle.jpg', align = "right",width=100,height=100),
# make sure you define the right (full) path

sidebarLayout(
  sidebarPanel(
    radioButtons("dist", "Distribution type:",
                 c("Normal" = "norm",
                   "Uniform" = "unif",
                   "Log-normal" = "lnorm",
                   "Exponential" = "exp")),
    br(),

    sliderInput("n", 
                "Number of observations:", 
                 value = 500,
                 min = 1, 
                 max = 1000)
  ),


  mainPanel(
    tabsetPanel(type = "tabs", 
      tabPanel("Plot", plotOutput("plot")), 
      tabPanel("Summary", verbatimTextOutput("summary")), 
      tabPanel("Table", tableOutput("table"))
    )
  )
))

data <- reactive({
    dist <- switch(input$dist,
                   norm = rnorm,
                   unif = runif,
                   lnorm = rlnorm,
                   exp = rexp,
                   rnorm)

    dist(input$n)
  })

  # Generate a plot of the data. Also uses the inputs to build
  # the plot label. Note that the dependencies on both the inputs
  # and the data reactive expression are both tracked, and
  # all expressions are called in the sequence implied by the
  # dependency graph
  output$plot <- renderPlot({
    dist <- input$dist
    n <- input$n

    hist(data(), 
         main=paste('r', dist, '(', n, ')', sep=''))
  })

  # Generate a summary of the data
  output$summary <- renderPrint({
    summary(data())
  })

  # Generate an HTML table view of the data
  output$table <- renderTable({
    data.frame(x=data())
  })
```

You can remove the renderImage part and all the ui/server functions (as stated earlier), simply keeping the render functions and tabsets. My result:

enter image description here

timfaber
  • 2,060
  • 1
  • 15
  • 17
  • I'm sorry but it still doesn't work... In a folder I saved the *.Rmd file. And here I created a new folder named www. In this www folder I stored the image named logotitle.jpg. Must I install or library a further package to solve this issue? – tueftla May 30 '17 at 18:45
  • Hm yes that should do the trick, what version of knitr and shiny do you have? I'll add a screenshot showing my resulting page – timfaber May 31 '17 at 07:24
  • My shiny version is 1.0.3 and my knitr version is 1.15.1 and my RStudio version is a little bit older 0.99.902 – tueftla May 31 '17 at 07:59
  • Hm, that shouldn't be the issue. What is the resolution of the image? Do you see the placeholder icon on the right side of the screen (right-aligned)? And is the above image something you are looking for? – timfaber May 31 '17 at 08:16
  • The resolution of my image is big enough and I scaled it to `width=100,height=100`. Your image above is showing exactly what I want. When I push the "Run Document" button I get a placeholder icon with a question mark right-aligned with the dimesion I entered. – tueftla May 31 '17 at 09:26
  • And what's also surpising to me that I get a scrollbar on the right in contrast to your image. – tueftla May 31 '17 at 09:33
  • Hmm, the scrollbar could be due to the size of the viewerpane (try adjusting it or opening it in a new window (or are you already viewing the app in a seperate window?). The placeholder icon implies that the image is not correctly loaded or found. However, your www folder should do the trick. I updated the full script which works for me. Can you either send me a zip of the folder you are using or show me a screenshot when running the exact code I specified above? – timfaber May 31 '17 at 09:37
  • I'm finished. Hope that it's that what you expected. – tueftla May 31 '17 at 10:02
  • Crazy stuff, not sure why it doesn't work. As a final option you might update Rstudio (not sure if this matters; I use RStudio 1.0.143; R 3.4) and share the zip file using a dropbox link so I can run it on my computer. Whether or not this works can help deciding whether its computer-script related. – timfaber May 31 '17 at 10:24
  • Weird but I am not able to get your image either or mine using your script (which is identical). I solved it by providing the full path to the image like: `img(src='/Users/timfaber/Desktop/Stackoverflow/www/logotitle.JPG', align = "right",width=100,height=100)`, this should work too. I have no problem with the scroll bar using your script so this might still be a window size issue. – timfaber Jun 01 '17 at 07:53
  • Now it works to me too. Thanks for your patience and your awesome support. I assume that an additional issue was that I stored the files in a server drive and not in a locally drive like C:.. – tueftla Jun 01 '17 at 09:18
  • np :) The server drive might cause problems but then again it did not work for me before providing the full path, there might still be a very obvious thing we missed! – timfaber Jun 01 '17 at 09:25