Home > Back-end >  r2d3 Shiny: can't render a local image in D3, despite being able to render one using an URL
r2d3 Shiny: can't render a local image in D3, despite being able to render one using an URL

Time:12-17

I'm struggling to get r2d3 Shiny to render just a .png file. I'm able to do it if I use an URL in the .js file, but nothing is rendered if I use a relative path towards the exact same file, but stored locally. I've of course checked the local file exists, that there's no typo in the path, etc.

I've built a toy R Shiny app to reproduce the problem. It only renders a d3 chart, which itself is just displaying the RStudio logo in a .png file (comment/uncomment the 2 last lines of the .js file to see the problem). Why is that happening? How to get a local image to be displayed using r2d3? I've been looking for a solution for hours, in vain.

app.R

library(r2d3)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Reprex"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            
        ),

        # Show a plot of the generated distribution
        mainPanel(
            d3Output("d3Chart", width = "100%", height = "800px") # d3output is the kind of output needed for D3; it requires renderD3 on the server side
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$d3Chart <- renderD3({
        # generate bins based on input$bins from ui.R
        r2d3(script = "./reprex.js", d3_version ="6")
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

reprex.js

svg
  .append("image")
  .attr("class","expand")
  .attr("x", 0)
  .attr("y", 0)
  .attr('width', 50)
  .attr('height', 50)
  .style("opacity",1)
  .attr("xlink:href", "https://www.rstudio.com/wp-content/uploads/2018/10/RStudio-Logo.png"); // It works with that image but NOT with a local image. Why?
  //.attr("xlink:href", "./RStudio-Logo.png");

I'm using R-4.1.2 RStudio 1.4.1717 to run the Shiny app.

CodePudding user response:

Thanks to Geovany, this was solved. I added in app.R, before the ui function, addResourcePath("images", ".") , so that I can access the working directory my picture is stored in (here, where app.R is located) using the tag images. By replacing the last line of reprex.js with .attr("xlink:href", "images/RStudio-Logo.png"); (and letting the previous line commented), the picture was displayed.

  • Related