我正在尝试创建一个图,其中我不使用点来表示数据,而是使用行政边界的轮廓。
下面的代码说明了我要做的事情。只是一个简单的有序散点图。我现在陷入困境,试图用每个行政边界( )的多边形形状替换这些点nz_map。因为其中的多边形nz_map有自己的几何形状,所以我不确定如何将它们放置在绘图空间中的点的位置。
任何建议将不胜感激。
# load packages
library(tidyverse)
library(sf)
library(rnaturalearth)
# map of nz with administrative boundary
nz_map <- ne_states(country = "new zealand", returnclass = "sf")
# get regions of interest and calculate area
nz_map <- nz_map %>%
select(name, region) %>%
filter(region %in% c("South Island", "North Island")) %>%
mutate(area = as.vector(st_area(.)/1e6))
# convert to points to illustrate plotting
nz_map_pnts <- st_centroid(nz_map)
# plot
ggplot() +
geom_point(data = nz_map_pnts, aes(reorder(name, area), y = area)) +
labs(x = "Region",
y = "Area") +
theme_classic()+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
Run Code Online (Sandbox Code Playgroud)
一种选择是使用lapply并annotation_custom为每个区域添加地图。为此,我首先在笛卡尔坐标中创建一个空白图,将 s 映射name到 y 上x,将areas 映射到 y 上。然后使用 例如lapply循环区域以在所需坐标处添加该区域的地图:
library(ggplot2)
library(sf)
nz_map_split <- nz_map |>
transform(name = reorder(name, area)) |>
split(~name)
dat <- data.frame(
name = nz_map$name,
area = nz_map$area
) |>
transform(name = reorder(name, area))
ggplot(dat, aes(name, area)) +
geom_blank() +
lapply(
nz_map_split,
\(.data) {
#browser()
x <- as.numeric(.data$name)
y <- .data$area
annotation_custom(
ggplotGrob(ggplot(.data) +
geom_sf() +
theme_void()),
xmin = x - .5, xmax = x + .5,
ymin = y - 2000, ymax = y + 2000
)
}
) +
labs(
x = "Region", y = "Area"
) +
theme_classic() +
theme(
axis.text.x = element_text(
angle = 90, vjust = 0.5, hjust = 1
)
)
Run Code Online (Sandbox Code Playgroud)