R Leaflet. Group point data into cells to summarise many data points

倾然丶 夕夏残阳落幕 提交于 2021-01-27 07:53:36

问题


Morning, afternoon or evening.

I have the following positional data (adjusted from 'Count of sampling points within a grid cell')

# Demo data 
set.seed(123)
#
lat <- runif(1000, 46.5, 48.5)
lon <- runif(1000, 13,16)
#
pos <- data.frame(lon, lat)

Using the following:

ggplot(pos, aes(x = lon, y=lat)) + 
  geom_bin2d(bins = 25) +
  stat_bin_2d(aes(label=stat(count)), bins = 25, position="identity") +
  scale_fill_gradient(low = "white", high = "red")+
  theme_void()

gives:

Awesome, but,

I want to do the exact same in leaflet but cannot seem to find a straightforward solution. In reality I have over 5,000,000 data points.

Preferable when running the mouse over the cell, or using leaflets popup functionality, the number of data points for the cell will be shown.


回答1:


Here is my solution.. it uses the sf-package, as well as tim's amazingly fast leafgl-package...

sample data

# Demo data 
set.seed(123)
lat <- runif(1000, 46.5, 48.5)
lon <- runif(1000, 13,16)
pos <- data.frame(lon, lat)

code

library( sf )
library( colourvalues )
#use leafgl for FAST rendering of large sets of polygons..
#devtools::install_github("r-spatial/leafgl")
library( leafgl )
library( leaflet )

#create a spatial object with all points
pos.sf <- st_as_sf( pos, coords = c("lon","lat"), crs = 4326)
#create e grid of polygons (25x25) based on the boundary-box of the points in pos.sf
pos.grid <- st_make_grid( st_as_sfc( st_bbox( pos.sf ) ), n = 25 ) %>% 
  st_cast( "POLYGON" ) %>% st_as_sf()
#add count of points in each grid-polygon, based on an 
# intersection of points with polygons from the grid
pos.grid$count <- lengths( st_intersects( pos.grid, pos.sf ) )
#add color to polygons based on count
cols = colour_values_rgb(pos.grid$count, include_alpha = FALSE) / 255
#draw leaflet
leaflet() %>% 
  addTiles() %>% 
  leafgl::addGlPolygons( data = pos.grid,
                         weight = 1,
                         fillColor = cols,
                         fillOpacity = 0.8,
                         popup = ~count )

output



来源:https://stackoverflow.com/questions/62548277/r-leaflet-group-point-data-into-cells-to-summarise-many-data-points

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!