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))
Related
I am trying to use both hc_motion and hc_drilldown within a highcharter map.
I can manage to get the hc_motion working with the full map, and also a drilldown from a larger area to its smaller ones (UK Region to Local Authority in this instance).
However, after drilling-down and zooming back out again, the hc_motion is now frozen.
Why is this and is there anyway around it? Or are hc_motion and hc_drilldown not compatible?
While in this instance the drilldown is static, if it possible hc_motion within each drilldown would be ideal, although will no even bother trying if even a static can't be incorporated without affecting the hc_motion.
Anyway, example code is below, thanks!
region_lad_lookup = read_csv("https://opendata.arcgis.com/api/v3/datasets/6a41affae7e345a7b2b86602408ea8a2_0/downloads/data?format=csv&spatialRefId=4326") %>%
clean_names() %>%
select(
region_code = rgn21cd,
region_name = rgn21nm,
la_name = lad21nm,
la_code = lad21cd,
value = fid
) %>%
inner_join(
read_sf("https://opendata.arcgis.com/api/v3/datasets/21f7fb2d524b44c8ab9dd0f971c96bba_0/downloads/data?format=geojson&spatialRefId=4326") %>%
clean_names() %>%
filter(grepl("^E", lad21cd)) %>%
select(la_code = lad21cd),
by = "la_code"
)
region_map = read_sf("https://opendata.arcgis.com/api/v3/datasets/bafeb380d7e34f04a3cdf1628752d5c3_0/downloads/data?format=geojson&spatialRefId=4326") %>%
clean_names() %>%
select(
area_code = rgn18cd,
area_name = rgn18nm
) %>%
st_as_sf(crs = 27700) %>%
sf_geojson() %>%
fromJSON(simplifyVector = F)
year_vec = c(2015, 2016, 2017, 2018, 2019)
region_data = region_lad_lookup %>%
select(
area_code = region_code,
area_name = region_name
) %>%
distinct() %>%
crossing(year_vec) %>%
mutate(
value = runif(nrow(.)),
drilldown = tolower(area_name)
)
region_vec = region_data %>%
select(area_name) %>%
distinct() %>%
pull()
get_la_map = function(data, region_val){
data = data %>%
filter(region_name == region_val) %>%
select(
area_code = la_code,
area_name = la_name,
geometry
) %>%
st_as_sf(crs = 27700) %>%
sf_geojson() %>%
fromJSON(simplifyVector = F)
return(data)
}
get_la_data = function(data, region_val){
data = data %>%
filter(region_name == region_val) %>%
select(
area_name = la_name,
area_code = la_code,
value
)
return(data)
}
get_region_map_list = function(region_val){
output = list(
id = tolower(region_val),
data = list_parse(get_la_data(region_lad_lookup, region_val)),
mapData = get_la_map(region_lad_lookup, region_val),
name = region_val,
value = "value",
joinBy = "area_name"
)
return(output)
}
region_ds = region_data %>%
group_by(area_name) %>%
do(
item= list(
area_name = first(.$area_name),
sequence = .$value,
value = first(.$value),
drilldown = first(.$drilldown)
)
) %>%
.$item
highchart(type = "map") %>%
hc_add_series(
data = region_ds,
mapData = region_map,
value = "value",
joinBy = "area_name",
borderWidth = 0
) %>%
hc_colorAxis(
minColor = "lightblue",
maxColor = "red"
) %>%
hc_motion(
enabled = TRUE,
axisLabel = "year",
series = 0,
updateIterval = 200,
magnet = list(
round = "floor",
step = 0.1
)
) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = lapply(region_vec, get_region_map_list)
)
I want to add data labels for a treemap I have created. I am using this treemap for an image so having the pts and fgpct for each box would be helpful. I want what's listed in the tooltip and the legend to appear in each box.
My code:
library(highcharter)
gamelogs %>%
filter(slugTeam == "MEM") %>%
group_by(namePlayer) %>%
summarise(pts = sum(pts), fgpct = sum(fgm) / sum(fga)) %>%
hchart("treemap", hcaes(name = namePlayer, value = pts, color = fgpct)) %>%
hc_title(text = "Grizzlies Scoring") %>%
hc_subtitle(text = "Shaded by Field Goal %") %>%
hc_chart(
backgroundColor = '#FFFFFF' # Chart Background Color
) %>%
hc_exporting(enabled = TRUE,
filename = "Grizzlies Scoring")
My Output:
The output I would like:
This output would have the points 1,041 in the box and also the fgpct of 49% that is shown in the legend. Anyway to add the data labels using highcharter treemap?
Try this
gamelogs %>%
filter(slugTeam == "MEM") %>%
group_by(namePlayer) %>%
summarise(pts = sum(pts), fgpct = round(sum(fgm) / sum(fga),digits=2)) %>%
hchart("treemap", hcaes(name = namePlayer, value = pts, color = fgpct),
dataLabels = list(enabled = TRUE, format='{point.namePlayer}<br/>{point.pts} pts<br/>{point.fgpct} fgpct'),
tooltip = list(pointFormat = "{point.namePlayer}: {point.pts}, {point.fgpct}%")) %>%
hc_title(text = "Grizzlies Scoring") %>%
hc_subtitle(text = "Shaded by Field Goal %") %>%
hc_chart(
backgroundColor = '#FFFFFF' # Chart Background Color
) %>%
hc_exporting(enabled = TRUE,
filename = "Grizzlies Scoring") %>%
hc_tooltip(crosshairs = TRUE)
you will get this output
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
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