Is there a way to make popup graphs appear on hover (rather than click) in Mapview? Alternatively, is it possible for the graphs to appear open by default? Rather than produce my own reproducible example, I would defer to the example given with the R Mapview documentation.
I am fairly new to R and Mapview so any guidance is greatly appreciated!
I've just pushed an update to package leafpop which provides the popup functionality used in mapview. This should provide what you want (at least partly - as mapview() will still need to be updated). This allows you to now specify tooltip = TRUE in addPopupImages (in addPopupGraphs via ...). Note that it is encouraged to use addPopup* functions over the classic popup* functions because they also work in non-interactive setting, e.g. when saving a map locally.
library(sf)
library(leaflet)
library(lattice)
library(leafpop)
pt = data.frame(x = 174.764474, y = -36.877245)
pt = st_as_sf(pt, coords = c("x", "y"), crs = 4326)
p2 = levelplot(t(volcano), col.regions = terrain.colors(100))
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pt, group = "pt") %>%
addPopupGraphs(
list(p2)
, group = "pt"
, width = 300
, height = 400
, tooltip = TRUE
)
Not sure when and how to integrate this into mapview() as this is a bit more complicated than the classic popup* functions (because we need to know something about the map object we create with mapview before we create it...). In any case, I hope this is at least partly useful and helps resolve your issue.
Related
I am working with the R programming language. Using the following code, I made an interactive map with the "leaflet" library :
Lat = round(runif(5000,43,44), 4)
Long = round(runif(5000,79,80), 4)
a <- rnorm(5000,100,10)
map_data <- data.frame(Lat, Long, a)
map_data$Long = -1 * map_data$Long
#load libraries
library(leaflet)
library(leaflet.extras)
#make heatmap for variable "a"
leaflet(map_data) %>%
addTiles(group="OSM") %>%
addHeatmap(group="a", lng=~Long, lat=~Lat, max=.6, blur = 60)
Does anyone know if it is possible to understand the exact (math) formulas behind the coloring/shading in this map? I tried consulting the official documentation for the functions used to create this map (https://cran.r-project.org/web/packages/leaflet.extras/leaflet.extras.pdf) , but no where does it explain how the colors are finalized. I suspect that this somehow might be related to "kernel density estimation". Furthermore, I have a feeling that the "max" and the "blur" options are actually parameters used in the final coloring of this map.
Does anyone know if it is possible to understand the exact formula used behind the coloring?
Thanks
I have come across a beautiful chart on this webpage: https://ourworldindata.org/coronavirus and interested to know if we can build the same chart in R with functionality of having highlighted series as well as selecting any line on hovering ?
I have build static highlighted charts using gghighlight but those are not interactive.
Plotly can help in interaction but I think they don't work with gghighlight.
So how can we have the combination of both highlight and interactivity in charts as in the link shared on top ?
Is it possible to achieve same results in R ? It would be really helpful if someone could share an example or link that can help.
(UPDATE: May be I can manually highlight lines by creating a factor column instead of using gghighlight and then pass it to ggplotly but then can ggplotly or some other library provide similar results on hover ?)
(NOTE: Not looking for animation. Just need highlighted, hover over interactive chart)
Below is the snapshot of same chart hovered over US (This chart is also similar to the one shared in World Economic Forum many times.)
Using plotly you can use highlight() to achive this.
This is a slightly modified example from here:
library(plotly)
# load the `txhousing` dataset
data(txhousing, package = "ggplot2")
# declare `city` as the SQL 'query by' column
tx <- highlight_key(txhousing, ~city)
# initiate a plotly object
base <- plot_ly(tx, color = I("black")) %>%
group_by(city)
# create a time series of median house price
time_series <- base %>%
group_by(city) %>%
add_lines(x = ~date, y = ~median)
highlight(
time_series,
on = "plotly_hover",
selectize = FALSE,
dynamic = FALSE,
color = "red",
persistent = FALSE
)
I know that I can use mapview::mapshot to export a leaflet map from Rstudio as a PNG. I have not been, however, able to precisely specify the zoom level and region of the map to be exported.
Borrowing some code from this answer to a related question let us consider the following MWE.
library(maps)
library(ggmap)
library(maptools)
library(leaflet)
library(mapview)
library(rgdal)
country <- 'italy';
zoomLevel <- 12;
ita.map <- map( country, fill = TRUE, col = 1, plot = F );
ita.map.ids <- sapply( strsplit( ita.map$names, ':' ), function(x) x[1] );
ita.sp <- map2SpatialPolygons( ita.map, IDs=ita.map.ids, proj4string=CRS("+proj=longlat +datum=WGS84"))
bb<-as.numeric(ita.sp#bbox)
m<-leaflet() %>%
setView(12.48,41.89,zoom=zoomLevel) %>%
addTiles() %>%
addPolygons(data=ita.sp)%>%
addExtent(data=ita.sp)
mapshot(m, file = "italy.png")
results in This is the correct zoom level but clearly does not contain all of Italy.
Adding
%>% fitBounds(bb[1],bb[2],bb[3],bb[4])
to the code above yields which is better, but a) does not respect the specified zoom level, and b) has a lot of unwanted horizontal padding.
I presume that adding width and height arguments to the leaflet() call would help but I am unsure how to automatically obtain the correct values. Also the resulting image would be very large necessitating a reduction in resolution.
How can I export the region of the map containing Italy at a specified zoom level without additional padding?
I dont know that what you want is possible (zoom = 12 and all of italy)...the two things seem mutually exclusive to me... unless you have a enormous figure... as you suggested.
I dont know for certain, but maybe the answer to your padding question is in the vwidth option of webshot. I suppose your figure needs to be taller than wide, so vwidth < vheight...
mapshot(m, file = "italy.png", vwidth = 700, vheight = 744)
I want to make a Shiny app where the colouring of a choropleth is based on a numeric value of one of many possible quantitative variables that a user can select from. In simple cases, this is straightforward, but I'm unsure of the best practices when we have 20+ variables, with quite detailed shape files (~2300 polygons).
It might or might not be relevant that the variables might be completely independent to each other such as 'Total Population' or 'Average Temperature' but some of them will have a temporal relationship such as 'Total Population' at 3 or more points in time.
One of the main shapefiles I am using is the ABS Statistical Area 2. Below I give the population density (total population/area) for Australia and a zoomed in view of Sydney to better convey the level of detail I'm interested in.
Australia
Sydney
I have read the shapefile in to R and greatly reduced the complexity/number of points using the ms_simplify() function in the rmapshaper package.
Now as far as Shiny and leaflet go, this is what I have been doing:
Before the server object is defined in server.R, I build a primary map object with all the desired 'layers'. That is, a leaflet with numerous addPolygon() calls to define the colouring of each 'layer' (group).
# Create main map
primary_map <- leaflet() %>%
addProviderTiles(
providers$OpenStreetMap.BlackAndWhite,
options = providerTileOptions(opacity = 0.60)
) %>%
# Layer 0 (blank)
addPolygons(
data = aus_sa2_areas,
group = "blank"
) %>%
# Layer 1
addPolygons(
data = aus_sa2_areas,
fillColor = ~palette_layer_1(aus_sa2_areas$var_1),
smoothFactor = 0.5,
group = "layer_1"
) %>%
...
# Layer N
addPolygons(
data = aus_sa2_areas,
fillColor = ~palette_layer_n(aus_sa2_areas$var_n),
smoothFactor = 0.5,
group = "layer_n"
) %>% ...
All bar the first layer is then hidden using hideGroup() so that the initial rendering of the map doesn't look silly.
hideGroup("layer_1") %>%
hideGroup("layer_2") %>%
...
hideGroup("layer_n")
In the Shiny app, using radio buttons (layer_selection), the user can select the 'layer' they'd like to see. I use observeEvent(input$layer_selection, {}) to watch the status of the radio button options.
To update the plot, I use leafletProxy() and hideGroup() to hide all the groups and then showGroup() to unhide the selected layer.
I apologize for the lack of reproducible example.
Questions
How can I optimise my code? I am eager to make it more performant and/or easy to work with. I've found using hideGroup()'s/showGroup() for each layer selection is far faster than using addPolygon() to a blank map, but this causes the app to take a very significant amount of time to load.
Can I change the variable I am colouring the polygons by, without redrawing or adding those polygons again? To clarify, if I have 2 different variables to plot, both using the same shape data, do I have to do 2 distinct addPolygon() calls?
Is there a more automatic way to sensibly colour the polygons for each layer according to a desired palette (from the viridis package?). Right now I'm finding defining a new palette for each variable, rather cumbersome, eg:
palette_layer_n <- colorNumeric(
palette = "viridis",
domain = aus_sa2_areas$aus_sa2_areas$var_n
)
Side Question
How does this map on the ABS website work? It can be incredibly detailed and yet extremely responsive. Compare the Mesh Block detail to the SA2 (2310 polygons), example below:
Since you haven't gotten any answers yet, I'll post a few things that can maybe help you, based on a simple example.
It would of course be easier if yours was reproducible; and I suppose from looking around you have already seen that there are several related issues / requests (about re-coloring polygons), whereas it doesn't seem that a real solution has made it into any release (of leaflet) yet.
With the below work-around you should be able to avoid multiple addPolygons and can cover an arbitrary number of variables (for now I have just hard-coded a single variable into the modFillCol call though).
library(leaflet)
library(maps)
library(viridis)
mapStates = map("state", fill = TRUE, plot = FALSE)
# regarding Question 3 - the way you set the domain it looks equivalent
# to just not setting it up front, i.e. domain = NULL
myPalette <- colorNumeric(
palette = "viridis",
domain = NULL
)
mp <- leaflet(data = mapStates) %>%
addTiles() %>%
addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)
# utility function to change fill color
modFillCol <- function(x, var_x) {
cls <- lapply(x$x$calls, function(cl) {
if (cl$method == "addPolygons") {
cl$args[[4]]$fillColor <- myPalette(var_x)
}
cl
})
x$x$calls <- cls
x
}
# modify fill color depending on the variable, in this simple example
# I just use the number of characters of the state-names
mp %>%
modFillCol(nchar(mapStates$names))
I'm trying to get de precipation radar data from the KNMI loaded in a leaflet in R. The data is located here: http://adaguc.knmi.nl/contents/webservices/WebServices_RADNL_OPER_R___25PCPRR_L3.html
So far, I've managed to get the current radar image to a leaflet layer with the following code:
require("leaflet")
require("dplyr")
leaflet() %>% addTiles() %>%
addWMSTiles(
"http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi",
layers = "RADNL_OPER_R___25PCPRR_L3_KNMI",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "KNMI"
)
So far so good...
But what I really would like, is to get a radar image from a given timestamp. The series goes back to 2009 (see example from the KNMI viewer here: http://geoservices.knmi.nl/viewer2.0/?srs=EPSG%3A3857&bbox=-725.7203842048766,6500000,1220725.7203842048,7200000&service=http%3A%2F%2Fgeoservices.knmi.nl%2Fcgi-bin%2FRADNL_OPER_R___25PCPRR_L3.cgi%3F&layer=RADNL_OPER_R___25PCPRR_L3_COLOR%24image%2Fpng%24true%24default%241%240&selected=0&dims=time$current&baselayers=streetmap$world_line ).
On the web, I have found several examples of leaflet that supports dates/times, (like this: http://apps.socib.es/Leaflet.TimeDimension/examples/example14.html), but unfortunalety I lack the skills to convert this example to the R-version of leaflet.
Can this be done? Can I, for example, retrieve the precipation radar image from 2017-01-07T04:00? If yes: where would/could I start?
Or if it cannot be done with leaflet; any other suggestions?
That was easier than expected ;-)
I just had to add a TIME-variable in the WMSTileOptions.
This works:
require("leaflet")
require("dplyr")
leaflet() %>% addTiles() %>%
addWMSTiles(
"http://geoservices.knmi.nl/cgi-bin/RADNL_OPER_R___25PCPRR_L3.cgi",
layers = "RADNL_OPER_R___25PCPRR_L3_COLOR",
options = WMSTileOptions(format = "image/png", transparent = TRUE, TIME = "2017-01-07T04:00:00"),
attribution = "KNMI neerslagradar"
)