我有一张特定的地图,我想在其中添加国家之间的线条,然后再添加线条粗细。下面的代码运行,但地图上没有显示任何内容。请注意,
df
是用ne_countries()
创建的,但我st_transform
将地图映射到罗宾逊投影,所以我不确定df的坐标是否正确。
我知道在地图上绘制线条的方法有很多,但我不确定 geom_segment 是最好的,所以我愿意接受其他解决方案。我可以先添加点,然后再添加线,我已经见过这种方法,但也无法实现。
library(ggplot2)
library(sf)
library(rnaturalearth)
library(dplyr)
library(rgdal)
#creating the map:
# Download countries polygons
shp <- ne_countries(type = "countries",
scale = "medium",
returnclass = "sf") |>
# transform to desired projection
st_transform("ESRI:54030")
shp <- subset(shp, select = -c(1:17, 19:63))
# Creating df with long and lat
countries <- ne_countries()
countries$longitude <- coordinates(countries)[,1]
countries$latitude <- coordinates(countries)[,2]
countries_xy <- countries@data %>%
select(admin, longitude, latitude)
# Joining long and lat to origin & destination
df1 <- tibble(origins = sample(c('Australia'),
size = 1, replace = TRUE),
destinations = sample(c('Fiji', 'Papua New Guinea', 'Sweden'),
size = 3, replace = FALSE))
df2 <- df1 %>%
left_join(countries_xy, by = c('origins' = 'admin')) %>%
left_join(countries_xy, by = c('destinations' = 'admin'))
df2$longitude.y <- as.numeric(as.character(df3$longitude.y))
df2$latitude.y <- as.numeric(as.character(df3$latitude.y))
# Merging shp and df
shp <- merge(shp,df2, by = "name", all.x = TRUE)
# Drawing the lines on the map (note that I also color the map with a discrete variable, but I don't think that is important here)
shp |>
ggplot() +
geom_sf(aes(fill = discrete_var)) +
geom_segment(aes(x = latitude.x,
y = latitude.y,
xend = longitude.x,
yend = longitude.y),
color = "white") +
scale_fill_brewer(palette = 'Purples', direction=-1, na.value="grey", drop = FALSE) +
coord_sf(expand = FALSE)
我知道还有很多其他在地图上画线的方法,但我不确定
geom_segment
是最好的,所以我愿意接受其他解决方案。
如果空间数据都是空间对象(sf、sfc、SpatRaster 等),则绘制和分析空间数据会更容易。因此,这里有一种将线条创建为 sf 对象的方法。
从您的代码中不清楚您希望行在哪里终止,并且您的代码中存在一些语法错误,因此我在此示例中任意使用了国家/地区质心。如果您愿意,可以使用
st_nearest_points()
,但我相信质心对于您要映射的内容来说是视觉上更好的选择。如果您希望线路在不同位置终止,请在下面评论。
library(sf)
library(dplyr)
library(rnaturalearth)
library(ggplot2)
# Create world map in Robinson projection
countries <- ne_countries() %>%
st_transform("ESRI:54030")
# Subset countries of interest and add lines between Australia and the rest
sf_line <- countries %>%
select(admin) %>%
filter(admin %in% c("Australia", "Fiji", "Papua New Guinea", "Sweden")) %>%
mutate(to = st_centroid(geometry)) %>%
st_set_geometry("to") %>%
select(-geometry) %>%
mutate(from = to[admin == "Australia"],
line_geom = st_union(to, from, by_feature = TRUE)) %>%
filter(!admin == "Australia") %>%
st_set_geometry("line_geom") %>%
st_cast("LINESTRING")
ggplot() +
geom_sf(data = countries, colour = "grey50") +
geom_sf(data = sf_line, colour = "#CD0BBC", linewidth = 1)