[英]Points not added to the map plot
我需要使用簡單的points
function 為 map 添加一些點。 問題是積分不會添加到 map。 這是一個簡單的命令,我按照一些教程向 map 添加點以這種方式工作,但在我的情況下不是這樣。 Plot
function 正確繪制德州等值線,但下一行( points
)根本沒有向 map 添加點:
library(rgdal)
library(rgeos)
library(sp)
companies <- read.csv('geoloc_data_comp.csv', header = T, dec = ',', sep = ';')
states <- readOGR('.', 'states')
plot(states[states@data$stat_name == 'texas',])
points(companies$coords.x1, companies$coords.x2, pch = 21)
首先,您應該開始避免rgeos
/ rgdal
,因為它們將停止維護。 見: https://github.com/r-spatial/evolution
sf
正在替換它們:
library(sp)
library(sf)
library(spData) #used because I wanted US states
# list of data in spData you have one with US states
data(package = "spData")
如果您想讀取 shapefile 或其他 GIS 格式,請檢查sf::st_read()
(而不是readOGR()
)
# one way with sf
plot(us_states$geometry[us_states$NAME == "Texas"])
# if you want do use the sp way
us_sp <- as(us_states, "Spatial") # convert to sp
plot(us_sp[us_sp@data$NAME == "Texas",])
使用sf
您將幾何圖形放在一列中(請參閱“幾何”),而不是使用帶有嵌套列表的 R S4(請參閱@data 和 @polygones)。
在獲得一些分數之前,我們需要檢查我們的數據在哪個 CRS 中。 如果你不知道 CRS 我喜歡這個網站: https://ihatecoordinatesystems.com/
您還可以在 us_states 文檔中找到信息: https://www.rdocumentation.org/packages/spData/versions/2.0.1/topics/us_states
然后你可以使用:
sp::proj4string(us_sp)
sf::st_crs(us_states)
# This is EPSG 4269 or NAD83
如果你想使用points()
他們需要在這個坐標系中(我懷疑這解釋了你的麻煩,即不同的 CRS)。
你沒有提供數據點,所以我制作了一些:
library(osmdata)
#this will just download node matching the key/value place=city
some_city_in_texas <- osmdata::opq(osmdata::getbb("Texas US"),
nodes_only = TRUE) %>%
osmdata::add_osm_feature(key = "place", value = "city") %>%
osmdata::osmdata_sf() #keep them in sf format
# osmdata_sp() also exist
class osmdata 有點復雜,但在這里你只需要知道some_city_in_texas$osm_points
為我們提供了點(測試points()
)。 現在我們可以檢查他們的 CRS:
sf::st_crs(some_city_in_texas$osm_points)
如您所見,我們在另一個 CRS 中,因此我們需要對其進行轉換。 (您可能需要這樣做)。
city_in_texas <- sf::st_transform(some_city_in_texas$osm_points,
4269)
sf
使用簡單的特征標准來存儲定位, points()
需要兩個向量 x&y。 您還應該檢查(錯誤的常見原因):R 使用 x/y (long/lat) 而不是 lat/long。
在這里,我們將city_in_texas
轉換為坐標。 (如果您需要做相反的事情,即將帶有 X/Y 的數據幀轉換為 sf object 看sf::st_as_sf()
)
coords_city <- sf::st_coordinates(city_in_texas)
最后,這現在可以正常工作了:
plot(us_states$geometry[us_states$NAME == "Texas"])
points(coords_city, pch = 21)
好的資源是https://r-spatial.org/和https://geocompr.robinlovelace.net/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.