I have a database of medical consultations by cities. I use the leaflet and state_popup function to display the results on a map, as described below:
pal <- colorBin("Blues",domain = DATA$QUANTITY_MEDICAL,bins = c(1, 1000, 5000, 10000, 50000,100000,300000),na.color=NA)
state_popup <- paste0("<strong>CITY: </strong>",
DATA$CITY,
"<br><strong> QUANTITY OF MEDICAL CONSULTATION: </strong>",
DATA$QUANTITY_MEDICAL)
leaflet(data = DATA) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(fillColor = ~pal(QUANTITY_MEDICAL),
fillOpacity = 0.7,
color = "#BDBDC3",
weight = 1,
popup = state_popup) %>%
addLegend("topright","bottomright", pal = pal, values = ~ DATA$QUANTITY_MEDICAL,
title = " QUANTITY OF MEDICAL CONSULTATION ",
opacity = 1)
This script only shows one result at a time (medical consultations). I would like to include information about other medical procedures that I want to include, such as exams or hospitalizations.
I want for each procedure (medical consultation, exams or hospitalization) to include a button that would change the result. In my database (DATA) I already have the columns that separate the procedures I quoted. Is it possible to include this button to change the results on the map?
You are going to have to define groups it seems to me. There is a good link from RStudio on leaflet that may help you.
https://rstudio.github.io/leaflet/showhide.html
Here is some sample code from that site:
quakes <- quakes %>%
dplyr::mutate(mag.level = cut(mag,c(3,4,5,6),
labels = c('>3 & <=4', '>4 & <=5', '>5 & <=6')))
quakes.df <- split(quakes, quakes$mag.level)
l <- leaflet() %>% addTiles()
names(quakes.df) %>%
purrr::walk( function(df) {
l <<- l %>%
addMarkers(data=quakes.df[[df]],
lng=~long, lat=~lat,
label=~as.character(mag),
popup=~as.character(mag),
group = df,
clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = F),
labelOptions = labelOptions(noHide = F,
direction = 'auto'))
})
l %>%
addLayersControl(
overlayGroups = names(quakes.df),
options = layersControlOptions(collapsed = FALSE)
)
I have a map I update monthly that has layers of information and I get it like so:
lsl <- unique(origAddress$LIHN_Line) # Gets unique service lines
# Create color palette
lihnpal <- colorFactor(
palette = 'Dark2'
, domain = origAddress$LIHN_Line
)
# create initial leaflet
LIHNMap <- leaflet() %>%
setView(lng = sv_lng, lat = sv_lat, zoom = sv_zoom) %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addControl("LIHN Service Line Point Map", position = "topright")
# for loop to cycle through adding layers
for(i in 1:length(lsl)){
LIHNMap <- LIHNMap %>%
addCircles(
data = subset(origAddress, origAddress$LIHN_Line == lsl[i])
, group = lsl[i]
, lat = ~lat
, lng = ~lon
, radius = 3
, fillOpacity = 1
, color = ~lihnpal(LIHN_Line)
, label = ~htmlEscape(LIHN_Line)
, popup = ~as.character(
paste(
"<strong>Hospitalist/Private: </strong>"
, hosim
, "<br><strong>Address: </strong>"
, FullAddress
, "<br><strong>Service Line: </strong>"
, LIHN_Line
, "<br><strong>LOS: </strong>"
, LOS
, "<br><strong>SOI: </strong>"
, SOI
, "<br><strong>Encounter: </strong>"
, pt_id
, "<br><strong>Payer Group:</strong>"
, pyr_group2
)
)
)
}
# add layercontrol
LIHNMap <- LIHNMap %>%
addLayersControl(
baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
overlayGroups = lsl,
options = layersControlOptions(
collapsed = TRUE
, position = "topright"
)
)
LIHNMap <- LIHNMap %>%
addAwesomeMarkers(
lng = sv_lng
, lat = sv_lat
, icon = hospMarker
, label = ""
, popup = HospPopup
)
# print map
LIHNMap
Related
I am working on Shiny and I would like to capture with a ObserveEvent the group/BaseGroup that the user is clicking in the legend of the following map:
output$map <- renderLeaflet({
p <- leaflet(paises_total_casos()) %>%
addTiles() %>%
setView( lat=10, lng=0 , zoom=2) %>%
addCircles(lng = ~cent$x, lat = ~cent$y, weight = 1, radius = ~sqrt(total_casos) * 40, color = "blue", group = "New_cases",
label = ~htmlEscape(paste(location, ":", format(as.numeric(total_casos), big.mark=","), sep = " "))) %>%
addCircles(lng = ~cent$x, lat = ~cent$y, weight = 1, radius = ~sqrt(total_fallecidos) * 40, color = "red", group = "New_deaths",
label = ~htmlEscape(paste(location, ":", format(as.numeric(total_fallecidos), big.mark=","), sep = " "))) %>%
addCircles(lng = ~cent$x, lat = ~cent$y, weight = 1, radius = ~sqrt(tests) * 40, color = "green", group = "New_tests",
label = ~htmlEscape(paste(location, ":", format(as.numeric(tests), big.mark=","), sep = " "))) %>%
#Afegim el Layers Control
addLayersControl(baseGroups = c("New_cases", "New_deaths", "New_tests"),
options = layersControlOptions(collapsed = FALSE))
})
Let's say I would like to capture if the map is showing the group New_cases, New_deaths or New_tests.
Is there a possibility to do that with ObserveEvent?
Thank you
You can include an observer for your map. You can use input$map_groups (adding "_groups" to the outputId used) and place inside observe. See complete example below which will print the map layer shown.
library(shiny)
library(leaflet)
ui <- fluidPage(leafletOutput("map"))
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>%
addTiles(group = "OpenStreetMap") %>%
addProviderTiles("Stamen.Toner", group = "Toner by Stamen") %>%
addMarkers(runif(20, -75, -74), runif(20, 41, 42), group = "Markers") %>%
addLayersControl(
baseGroups = c("OpenStreetMap", "Toner by Stamen"),
overlayGroups = c("Markers")
)
})
observe({
print(input$map_groups)
})
}
shinyApp(ui, server)
Using the renderLeaflet (following codes), I am trying to create an interactive map within shiny. I want the map to be updated based on users selections of age group, sex, and year. When age group=60 and sex=both sexes and year= 2010 are selected, everything looks great (please see this screen shot).
However, when the other age groups are selected, the legend remains unchanged and is not rendered (Please see the second screen shot).
Here is my code:
mapdata_ <- reactive ({
nhmap$Per <- round(nhmap$Per, 1)
out_map <- nhmap %>%
filter (
Age_Group %in% input$Age_Group_map,
Sex %in% input$sex_map,
Year %in% input$Year_map)
return(out_map)
})
output$int_map <- renderLeaflet ({
leaflet (mapdata_(),
pal8 <- c("#FFFFE5", "#D9F0A3", "#78C679", "#006837") ,
pal <- colorBin(palette = pal8, domain = nhmap$Per, bins=4, right =FALSE, na.color = "#808080", alpha = FALSE, reverse = F)
) %>%
addProviderTiles("CartoDB.Positron") %>%
clearControls() %>%
clearShapes()%>%
addPolygons(fillColor = ~pal(Per),
stroke=T,
weight=1,
smoothFactor=0.2,
fillOpacity = 1,
color="black",
popup=~paste(NAME,"<br>",input$sex_map,
input$Age_Group_map,"=",Per,"%"),
highlightOptions = highlightOptions(color = "red",
weight = T,
bringToFront = T),
label=~NAME) %>%
addTiles() %>%
setView(-82.706838, 40.358615, zoom=7) %>%
addLegend(position = "bottomright",
values = ~pal(Per),
pal = pal,
title = (paste("%",input$Age_Group_map, input$sex_map, "in", input$Year_map)) ,
labFormat = labelFormat())
})
I have the following code:
# Get unique list of groups needed
lsl <- unique(origAddress$LIHN_Line)
# create initial leaflet
mt <- leaflet() %>%
setView(lng = sv_lng, lat = sv_lat, zoom = sv_zoom) %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite")
# for loop to cycle through adding layers
for(i in 1:length(lsl)){
#l <- lsl[i]
mt <- mt %>%
addCircles(
data = subset(origAddress, origAddress$LIHN_Line == lsl[i])
, group = lsl[i]
, radius = 3
, fillOpacity = 0.6
)
}
# add layercontrol
mt <- mt %>%
addLayersControl(
baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
overlayGroups = lsl,
options = layersControlOptions(collapsed = TRUE
, position = "bottomright")
) %>%
showGroup("Medical")
# print map
mt
The issue is that the showGroup() function is not working as I expected. I checked the element of the map and got the following:
<span> Medical</span>
So I am not understanding why only that group isn't showing.
I have a couple of columns with categorical data. I would like to create layers from these categorical data and plot them against a base map in R with leaflet. Each of these columns has 4 or more categories.
I am completely lost on how to attack this problem. I tried to do one category from one column and I got all points on the map back and the layer controlled all points which was not the expected behavior.
Here is what I have:
lihn_map <- leaflet(origAddress) %>%
setView(lng = sv_lng, lat = sv_lat, zoom = sv_zoom) %>%
addTiles(group = "OSM (default)") %>%
addCircleMarkers(data = origAddress
, radius = 3
, fillOpacity = 1
, group = "MI"
) %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
# Overlay groups
addCircles(~lat, ~lon, group = "MI") %>%
addLayersControl(
baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
overlayGroups = "MI",
options = layersControlOptions(collapsed = FALSE)
)
lihn_map
I am trying this loop, it adds the groups to the layer control but the selection does not change the map:
lsl <- unique(origAddress$LIHN_Line)
mt <- leaflet() %>%
addTiles(group = "OSM (default)") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite")
for(i in 1:length(lsl)){
l <- lsl[i]
mt <- mt %>%
addCircleMarkers(
# I have also tried
data = subset(origAddress, LIHN_Line = lsl[i])
data = origAddress
, group = lsl[i]
, radius = 3
, fillOpacity = 0.6)
}
mt <- mt %>%
addLayersControl(
baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
overlayGroups = lsl,
options = layersControlOptions(collapsed = FALSE
, position = "bottomright")
)
mt
My expectation is that this layer would only control the subset of data where the group is equal to MI Maybe I have to create subset data.frames? This seems inefficient if so and I'm sure is not the answer.
I performed the following and it worked:
# for loop to cycle through adding layers
for(i in 1:length(lsl)){
l <- lsl[i]
mt <- mt %>%
addCircles(
data = subset(origAddress, origAddress$LIHN_Line == lsl[i])
#data = origAddress
, group = lsl[i]
, radius = 3
, fillOpacity = 0.6)
}
using subset worked brilliantly
i'm tryng to plot several layer of addCircleMarkers with leaflet package and i need a shorter method to do it
now i'm doing this :
data_stack <- data.frame(lat=rnorm(10),lng=rnorm(10) ,v1=rnorm(10,10), v2=rnorm(10,20) , v3=rnorm(10,20), v4=rnorm(10,20), v5=rnorm(10,20) )
map_test_global <- leaflet(data_stack) %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addCircleMarkers(radius = ~ v1,fill = T,fillColor ="red",popup =~as.character(v1) ,group="1" )%>%
addCircleMarkers(radius = ~ v2, fill = T , fillColor ="green" ,popup = ~ as.character(v2) ,group="2" ) %>%
addCircleMarkers(radius = ~ v3, fill = T , fillColor ="blue" ,popup = ~ as.character(v3) ,group="3" ) %>%
addCircleMarkers(radius = ~ v4, fill = T , fillColor ="DarkOrange" ,popup = ~ as.character(v4) ,group="4" ) %>%
addCircleMarkers(radius = ~ v5, fill = T , fillColor ="DarkOrange" ,popup = ~ as.character(v5) ,group="5" ) %>%
addLayersControl( baseGroups = c("1", "2","3","4","5"),
options = layersControlOptions(collapsed = FALSE))
and i need to do it for 200 column
im trying to do it like this but it'isn't working
map_test_global <- leaflet(data_stack) %>%
addTiles() %>% # Add default OpenStreetMap map tiles
lapply( list_var ,function(x)
addCircleMarkers(map_test_global ,radius= reformulate(x),popup = reformulate(x) ,group=x )
)
addLayersControl(map_test_global ,
baseGroups = list_var,
options = layersControlOptions(collapsed = T)
)
it plot each map in different window andthe last one is empty (only layercontrol showing)
i know popup isn't working i need to as.character dataframe before
Thank you
You are not changing map_test_global in your apply.
You could try a loop:
map_test_global <- leaflet(data_stack) %>%
addTiles()
for(x in 1:5){
map_test_global <- map_test_global %>% addCircleMarkers(radius = as.formula(paste0("~v",x)),fill = T,fillColor ="red",popup =as.formula(paste0("~as.character(v",x,")")) ,group=as.character(x))
}
map_test_global %>% addLayersControl( baseGroups = as.character(1:5),
options = layersControlOptions(collapsed = FALSE))