且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

传单上路线的不同部分有多少不同的颜色? [R Studio]

更新时间:2023-01-03 22:53:39

当使用空间数据时,它有助于了解空间类!我假设你知道锄头将您的JSON文件作为数据框读取到R中。



这是一个可重复的示例:



$(



###创建一些带有坐标的随机数据(data(breweries91,package =mapview))
set.seed(123)
dat lon =坐标(breweries91)[,1],
lat = coordinates(breweries91)[,2])

###创建线条状态条件
cond
###循环通过条件并为每个条件创建一个SpatialLines对象
lns< - lapply(seq(cond),function(i){

ind< - dat $ val == cond [i]
sub_dat< - dat [ind,]

coords ln
proj4string(ln)< - + init = epsg: 4326
return(ln)
})

### view map
mapview(lns [[1]],col =darkred)+
mapview(lns [[2]],col =forestgreen)+
mapview lns [[3]],col =cornflowerblue)

本质上,我们在这里做的是为我们指定的每个条件创建一个有效的sp :: SpatialLines对象。给定您提到的交互性,我们绘制使用 mapview 的那些。空间对象的绘制可以通过多种方式实现( base 格子 ggplot2 单张,... )所以有很多选择可供选择。看看 sp Gallery ,获得一个不错的教程。



注意:此答案仅适用于非投影地理坐标(即纬度/经度)!


I have a JSON file of a long route. The file contains the lat and long of of this route.

I'm trying to mark different sections of this route based on a set of criteria (which I've compiled in a dataframe). However, I'm facing to problems:

1) How do I break up this long set of lat and longs into segments? (can't do this manually because I have many route variations)

2) How do I assign a variable color to each segment?

I intend to use leaflet map (for its interactivity), but I'm open to better suggestions.

When working with spatial data, it helps to know spatial classes! I am assuming you know hoe to read your JSON file as a data frame into R.

Here's a reproducible example:

library(mapview)
library(sp)

### create some random data with coordinates from (data("breweries91", package = "mapview"))
set.seed(123)
dat <- data.frame(val = as.integer(rnorm(32, 10, 2)),
                  lon = coordinates(breweries91)[, 1],
                  lat = coordinates(breweries91)[, 2])

### state condition for creation of lines
cond <- c(8, 9, 10)

### loop through conditions and create a SpatialLines object for each condition
lns <- lapply(seq(cond), function(i) {

  ind <- dat$val == cond[i]
  sub_dat <- dat[ind, ]

  coords <- cbind(sub_dat$lon, sub_dat$lat)
  ln <- coords2Lines(coords, ID = as.character(cond[i]))

  proj4string(ln) <- "+init=epsg:4326"
  return(ln)
})

### view lines with mapview
mapview(lns[[1]], col = "darkred") +
  mapview(lns[[2]], col = "forestgreen") +
  mapview(lns[[3]], col = "cornflowerblue")

Essentially, what we are doing here is create a valid sp::SpatialLines object for each condition we specify. The we plot those using mapview given you mentioned interactivity. Plotting of spatial objects can be achieved in many ways (base, lattice, ggplot2, leaflet, ...) so there's many options to choose. Have a look at sp Gallery for a nice tutorial.

Note: This answer is only valid for non-projected geographic coordinates (i.e. latitude/longitude)!