3

我正在努力让 r2d3 + Shiny 只渲染一个 .png 文件。如果我在 .js 文件中使用 URL,我可以做到这一点,但如果我使用指向完全相同文件的相对路径,则不会呈现任何内容,但存储在本地。我当然检查了本地文件是否存在,路径中没有错字等。

我已经构建了一个玩具 R Shiny 应用程序来重现该问题。它只呈现一个 d3 图表,它本身只是在 .png 文件中显示 RStudio 徽标(注释/取消注释 .js 文件的最后 2 行以查看问题)。为什么会这样?如何使用 r2d3 获取要显示的本地图像?我一直在寻找解决方案几个小时,徒劳无功。

应用程序.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");

我正在使用 R-4.1.2 + RStudio 1.4.1717 来运行 Shiny 应用程序。

4

1 回答 1

0

多亏了Geovany,这个问题得到了解决。我在 app.R 中添加了 ui 函数,addResourcePath("images", ".")这样我就可以使用标签访问我的图片存储在的工作目录(这里是 app.R 所在的位置)images。通过将reprex.js 的最后一行替换为.attr("xlink:href", "images/RStudio-Logo.png");(并让前一行注释掉),图片就显示出来了。

于 2021-12-15T10:01:33.697 回答