Generate random fake geographical data with conditions - r

I'm trying to think what is the best way to generate a fake map with some fake data that is random but follows some conditions. For example I want to have 8 dots east of the "Deleng" river and 12 west. I want the mean of the color to be higher east than west. Other than that, I want the points to be random
This is the code I have right now:
set.seed(7102015)
gen.schools <- function(n.schools){
School.long <- rnorm(n = n.schools, mean = 21.7672, sd = 0.025)
School.lat <- rnorm(n = n.schools, mean = 58.8471, sd = 0.025)
School.VAM <- rnorm(n = n.schools, mean = 0, sd = 1)
Schools <- data.frame(School.lat, School.long, School.VAM)
return(Schools)
}
district.map <- gen.schools(n.schools = 20)
library(leaflet)
# Create a continuous palette function
pal <- colorNumeric(
palette = "RdYlBu",
domain = district.map$School.VAM
)
leaflet() %>% addTiles("http://opengeofiction.net/osm_tiles/{z}/{x}/{y}.png") %>%
setView(lng = 21.7672, lat = 58.8471, 13) %>%
addCircleMarkers(data = district.map, lat = ~School.lat, lng =~School.long,
fillColor = ~pal(School.VAM),
stroke = FALSE, fillOpacity = 1) %>%
addLegend(position = "topright",
pal = pal, values = district.map$School.VAM,
title = "Performance Index",
opacity = 1
)
If using the river as a condition is not possible, can I superimpose a fine lat long grid to this fake map so I can pick the points by hand?
Thanks!

Related

r leaflet layers control (addLayersControl) does not hide legends belonging to a group

In the tiny example shown below, I have two features associated with each country (polygons) in the map, namely: randomA, randomB. Each feature has its own legend, so I armed a group named "randomA" containing the polygons coloured with feature randomA and its corresponding legend. I did the same for group "randomB". When the map is depicted, leaflet correctly shows or hides polygons for features "randomA" and "randomB". However legends are always shown stacked on the bottom right corner.
This is the code:
library(rgdal)
library(leaflet)
# From http://data.okfn.org/data/datasets/geo-boundaries-world-110m
countries <- readOGR("json/countries.geojson")
n <- nrow(countries)
# Add two random fields
set.seed(15)
countries#data$randomA <- rnorm(n, 1000, 250)
countries#data$randomB <- rnorm(n, 10000, 3000)
map <- leaflet(countries) %>% addTiles()
pal <- colorNumeric(
palette = "YlGnBu",
domain = countries$randomA
)
map <- map %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
color = ~pal(randomA), group = "randomA"
) %>%
addLegend("bottomright", pal = pal, values = ~randomA,
title = "random A",
labFormat = labelFormat(prefix = "$"),
opacity = 1, group = "randomA"
)
qpal <- colorQuantile("RdYlBu", countries$gdp_md_est, n = 5)
map <- map %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
color = ~qpal(randomB), group = "randomB"
) %>%
addLegend(
"bottomright",
pal = qpal,
values = ~randomB,
opacity = 1, group = "randomB"
)
# Finally control layers:
map <- map %>%
addLayersControl(
baseGroups = c("randomA", "randomB"),
position = "bottomleft",
options = layersControlOptions(collapsed = F)
)
map
A snapshot of the result is shown in the image below:
Also, in the actual problem I have to represent nine of these groups, so I wish I had all the legends in the same place.
Do you have any suggestion?
Try using overlay groups instead of base groups:
addLayersControl(
overlayGroups = c("randomA", "randomB"),
position = "bottomleft",
options = layersControlOptions(collapsed = F)
)

Counting how many point are in the polygon of region [R]

I would like to ask how to calculate number of point that are in some region when we have longtitue and latitude variables of point and polygon of country and its regions.
I provided example below:
I would like to calculate how many point are in what regions (including zero when there is no point) and than add this variables to data2#data object so one can use count measures to fill each regions polygons.
library(leaflet)
library(tidyverse)
set.seed(101)
URL2 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_FRA_2_sp.rds"
data2 <- readRDS(url(URL2))
URL3 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_ESP_2_sp.rds"
data3 <- readRDS(url(URL3))
URL4 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_PRT_2_sp.rds"
data4 <- readRDS(url(URL4))
URL5 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_GBR_2_sp.rds"
data5 <- readRDS(url(URL5))
random_long_lat <-
data.frame(
long = sample(runif(300, min = -2.5, max = 15.99), replace = F),
lat = sample(runif(300, min = 42.69, max = 59.75), replace = F)
)
all <- rbind(data2, data3, data4, data5)
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=all, stroke = TRUE, color = "black", weight="", smoothFactor = 0.95,
fill = F) %>%
addCircles(lng = random_long_lat$long, lat = random_long_lat$lat)
# Here add new variable called count, that would count how many point are in the region
all#data
I would like the result so one can calculate something like this:
all#data <-
all#data %>%
mutate(counts = rnorm(nrow(all), 100, sd = 20))
cuts <- c(0, 5, 20, 40, 80, 150, max(all#data$counts))
cuts <- colorBin("Greens", domain = all$counts, bins = cuts)
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=all, stroke = TRUE, color = "white", weight="", smoothFactor = 0.95,
fillOpacity = 0.65, fillColor = ~cuts(all$counts)) %>%
addLegend(pal = cuts,
values = all$counts,
labFormat = labelFormat(suffix = " "),
opacity = 0.85, title = "How many point were counted in each region", position = "topright")
however I dont know is it posible to calculate number of point in each regions having just coordinances?
If you transform the points and France polygons to sf objects, you can use st_intersects() to count the number of points in each polygon.
Note that I updated your sample points so that each quintile break in cuts is unique. With your original data, the first three quintiles were just 0 so the coloring in the leaflet map didn't work.
new sample data
library(leaflet)
library(tidyverse)
set.seed(101)
URL2 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_FRA_2_sp.rds"
data2 <- readRDS(url(URL2))
random_long_lat <-
data.frame(
long = sample(runif(1000, min = -2.5, max = 5.99), replace = F),
lat = sample(runif(1000, min = 42.69, max = 49.75), replace = F)
)
make sf objects and count points in polygons
library(sf)
data_sf <- data2 %>% st_as_sf()
random_long_lat_sf <- random_long_lat %>%
st_as_sf(coords = c("long", "lat"), crs = 4326)
data_sf_summary <- data_sf %>%
mutate(counts = lengths(st_intersects(., random_long_lat_sf)))
define breaks for legend and draw map
cuts <- quantile(data_sf_summary$counts, probs = seq(0, 1, 0.2))
cuts <- colorBin("Greens", domain = data_sf_summary$counts, bins = cuts)
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=data_sf_summary, stroke = TRUE, color = "white", weight="", smoothFactor = 0.95,
fillOpacity = 0.65, fillColor = ~cuts(data_sf_summary$counts)) %>%
addLegend(pal = cuts,
values = data_sf_summary$hdp,
labFormat = labelFormat(suffix = " "),
opacity = 0.85, title = "How many point were counted in each region", position = "topright")
Also note that tmap package, which lets you switch between static and interactive maps using the same syntax (which resembles ggplot syntax).
same map with tmap:
library(tmap)
tmap_mode("view") # make map interactive
tm_shape(data_sf_summary) +
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
title = "How many point were counted in each region")
static map with tmap:
library(tmap)
tmap_mode("plot") # make map static
tm_shape(data_sf_summary) +
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
title = "How many point were counted in each region") +
tm_layout(legend.position = c("right","top"))
For multiple countries
First create new sample points that cover Europe:
random_long_lat <-
data.frame(
long = sample(runif(1000, min = -7.5, max = 19.99), replace = F),
lat = sample(runif(1000, min = 38.69, max = 60.75), replace = F)
)
all <- rbind(data2, data3, data4, data5)
Then make the sf objects and find the counts of points in every polygon:
all_sf <- all %>% st_as_sf()
random_long_lat_sf <- random_long_lat %>%
st_as_sf(coords = c("long", "lat"), crs = 4326)
all_sf_summary <- all_sf %>%
mutate(counts = lengths(st_intersects(., random_long_lat_sf)))
qtm(random_long_lat_sf)
Option 1: Choose maps from a list object by name using the NAME_0 column.
tmap_mode("view") # make maps interactive
list_of_maps <- map(unique(all_sf_summary$NAME_0),
~ tm_shape(all_sf_summary %>%
filter(NAME_0 == .x)) + # filter the data for your country of interest
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
alpha = 0.85,
border.col = NA,
title = "How many point were counted in each region") +
tm_layout(legend.position = c("right","top"))) %>%
set_names(unique(all_sf_summary$NAME_0))
list_of_maps[['France']]
list_of_maps[['Portugal']]
Option 2: Show all the maps at once
### all maps at once
tm_shape(all_sf_summary) + # filter the data for your country of interest
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
alpha = 0.85,
border.col = NA,
title = "How many point were counted in each region") +
tm_layout(legend.position = c("right","top")) +
tm_facets(by = c("NAME_0"), ncol = 2, showNA = FALSE)

how to add points, colored according to the value of a variable, to a map?

Using these instructions: win.graph()
map("usa")
map("usa",col='white',fill=T, xlim=c(-73.7 ,-71.52), ylim=c(38.6,40.92))
points.geodata(x=dat_zero,coords=dat_zero$coords,dat_zero$data,pt.divide="quintiles",
col=1:5,xlim=c(-73.7 ,-71.52), ylim=c(38.6,40.92),add.to.plot = T)
not from mistakes but does not do it.
welcome to SO. Generally it's a good idea to include what packages you may have loaded and more description of the problem itself.
Here's an approach using plotly. I'm using ggplot2::map_data() to generate some sample data (larger dataset) and show how it works:
library(ggplot2)
library(plotly)
dat <- map_data(map = 'county')
# map_data() is a large dataset, I'm limiting the map to 50 observations
# the coords$value field is the variable that determines the color of the mapped point
coords <- dat[sample(sample(x = 1:nrow(dat), size = 50, replace = T)), ]
coords$value <- rnorm(n = nrow(coords), mean = 10, sd = 3)
# some code to let plotly know we're plotting a map (projection etc.)
g <- list(
scope = 'usa',
projection = list(type = 'Mercator'),
showland = TRUE,
landcolor = toRGB("gray85"),
subunitwidth = 1,
countrywidth = 1,
subunitcolor = toRGB("white"),
countrycolor = toRGB("white")
)
plt <- plot_geo(locationmode = 'USA-states', sizes = c(1, 250), data = coords) %>%
add_markers(x = ~long, y = ~lat, color = ~value) %>%
layout(title = 'County Map',
geo = g)
OUTPUT

Missing polygons while using Leaflet in R

I'm trying to reproduce a code to display polygons in a map in another computer, however, in one computer the polygons are not shown. Does someone had this kind of problem while sharing code?
You can download the shapefile from here: http://www.conabio.gob.mx/informacion/metadata/gis/muni_2012gw.xml?_xsl=/db/metadata/xsl/fgdc_html.xsl&_indent=no
library(rgdal)
library(rgeos)
library(leaflet)
Mex <- readOGR(dsn="C:/DISCO D", layer="Muni_2012gw")
Mex_sub <- Mex[Mex$CVE_ENT=="01",]
bins <- quantile(Mex_sub#data$OID_1, c(0,.125,.25, .5, .75,.875, 1))
pal <- colorBin("YlOrRd", domain = Mex_sub#data$OID_1, bins = (bins),
na.color = "grey40", reverse = FALSE)
centr <- gCentroid(Mex_sub)#coords
leaflet(Mex_sub, options = leafletOptions(minZoom = 4, maxZoom = 15)) %>%
addTiles() %>%
setView(centr[1], centr[2], zoom = 8) %>%
addPolygons(data=Mex_sub, weight = 1,fill = ~OID_1, fillColor = ~pal(OID_1),
opacity=1, fillOpacity = 0.5, color=grey(0.5))

How to add labels on top of polygons in leaflet

I am working with the leaflet R package. I have a zoning system made of polygons and I'd like to lay their IDs on top of them. Below is an illustration (with another software) of my objective.
Thanks for your suggestions!
Since there is no reproducible data, I decided to use one of my previous posts related to leaflet. There are two things you want to take away from this post: 1) you need to create a data frame containing center points of target regions, 2) you need to use addLabelOnlyMarkers(). You can achieve the first thing using gCentroid(). I added row names of the polygon data set (UK) as character to centers. This is used for labeling. You need to think what labels you use in your own case. Once this data set is ready, you want to use it in addLabelOnlyMarkers().
library(raster)
library(rgeos)
library(leaflet)
# Get UK polygon data
UK <- getData("GADM", country = "GB", level = 2)
# Find a center point for each region
centers <- data.frame(gCentroid(UK, byid = TRUE))
centers$region <- row.names(UK)
### Create dummy data
set.seed(111)
mydf <- data.frame(place = unique(UK$NAME_2),
value = sample.int(n = 1000, size = n_distinct(UK$NAME_2), replace = TRUE))
### Create five colors for fill
mypal <- colorQuantile(palette = "RdYlBu", domain = mydf$value, n = 5, reverse = TRUE)
leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 55, lng = -3, zoom = 6) %>%
addPolygons(data = UK,
stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
fillColor = ~mypal(mydf$value),
popup = paste("Region: ", UK$NAME_2, "<br>",
"Value: ", mydf$value, "<br>")) %>%
addLabelOnlyMarkers(data = centers,
lng = ~x, lat = ~y, label = ~region,
labelOptions = labelOptions(noHide = TRUE, direction = 'top', textOnly = TRUE)) %>%
addLegend(position = "bottomright", pal = mypal, values = mydf$value,
title = "UK value",
opacity = 0.3)

Resources