Вам необходимо добавить каталог, в котором хранятся ваши локальные изображения, в качестве ресурса c для веб-сервера Shiny. Это можно сделать с помощью addResourcePath
:
library(shiny)
library(shinydashboard)
library(plotly)
ui <- dashboardPage(
dashboardHeader(title = "Test"),
dashboardSidebar(),
dashboardBody(tags$head(tags$style(
HTML("img.small-img {
max-width: 75px;
}")
)),
plotlyOutput("hoverplot"))
)
server <- function(input, output, session) {
# create some local images
if(!dir.exists("myimages")){
dir.create("myimages")
}
myPlots <- paste0("myimages/myplot", seq_len(3), ".png")
for (myPlot in myPlots) {
png(file = myPlot, bg = "transparent")
plot(runif(10))
dev.off()
}
myImgResources <- paste0("imgResources/myplot", seq_len(3), ".png")
dt <- data.frame(
fruits = c("apple", "banana", "oranges"),
rank = c(11, 22, 33),
image_url = myImgResources
)
# Add directory of static resources to Shiny's web server
addResourcePath(prefix = "imgResources", directoryPath = "myimages")
output$hoverplot <- renderPlotly({
plot_ly(
dt,
x = ~ fruits,
y = ~ rank,
type = 'scatter',
mode = 'markers',
hoverinfo = 'none',
source = "hoverplotsource",
customdata = ~ image_url
) %>%
event_register('plotly_hover') %>%
event_register('plotly_unhover')
})
hover_event <- reactive({
event_data(event = "plotly_hover", source = "hoverplotsource")
})
unhover_event <- reactive({
event_data(event = "plotly_unhover", source = "hoverplotsource")
})
hoverplotlyProxy <- plotlyProxy("hoverplot", session)
observeEvent(unhover_event(), {
hoverplotlyProxy %>%
plotlyProxyInvoke("relayout", list(images = list(NULL)))
})
observeEvent(hover_event(), {
hoverplotlyProxy %>%
plotlyProxyInvoke("relayout", list(images = list(
list(
source = hover_event()$customdata,
xref = "x",
yref = "y",
x = hover_event()$x,
y = hover_event()$y,
sizex = 20,
sizey = 20,
opacity = 1
)
)))
})
}
shinyApp(ui = ui, server = server)
В качестве альтернативы вы можете хранить свои изображения в папке www
(подкаталог папки вашего приложения), после чего вы можете получить доступ к изображениям без префикса.
![Result](https://i.stack.imgur.com/5JaIp.gif)