I'm using leaflet in my shiny app and I want the app to open a window including a plot once the user clicks on the map. I have written the below code:
library(shiny)
library(leaflet)
library(plotly)
library(dplyr)
ui <- fluidPage(
leafletOutput("mymap"),
)
server <- function(input, output, session) {
points <- eventReactive(input$recalc, {
cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
}, ignoreNULL = FALSE)
output$mymap <- renderLeaflet({
leaflet() %>%
addProviderTiles(providers$Stamen.TonerLite,
options = providerTileOptions(noWrap = TRUE)
) %>%
addMarkers(data = points())
})
observeEvent(input$mymap_marker_click,{
df <- data.frame(x = 1:10, y = 1:10)
plt <- ggplot(df, aes(x,y)) + geom_line()
pltly <- ggplotly(plt)
showModal(modalDialog(
title = "Important message", size = "l",
pltly ))
})
}
shinyApp(ui, server)
This code kind of does the job but it shows the plot very compressed! and if you slightly drag the boundaries of the window to the left or right then it will be fixed but I want it to work without the need to do that for fixing the plot! Does anyone know a better way for doing it?
You can use renderPlotly
and plotlyOutput
to make and display the plot.
output$my_plotly <- renderPlotly({
df <- data.frame(x = 1:10, y = 1:10)
plt <- ggplot(df, aes(x,y)) + geom_line()
ggplotly(plt)
})
observeEvent(input$mymap_marker_click,{
showModal(modalDialog(plotlyOutput("my_plotly")))
})
The above solution works but there is an issue. In my real example, the plot uses an information from the click in the map such as (input$mymap_marker_click$id) to be created and thus I have to use another "observeEvent" before the "renderPlotly" to take the id and then generate the plot accordingly. The problem of this approach is that when you click on a different location, the second "observeEvent" runs faster and shows the previous region's plot until the first "observeEvent + rednerPlotly" is finished running and generating the new plot and only after that the modal updates itself.
Feel free to post a new question with that issue