我想为一列着色,但请使用
NA
将 ggplot2
值渲染为一种特定颜色。
如果我们从 world
包中获取 spData
数据集。
library(sf)
library(spData)
library(ggplot2)
set.seed(2018) # set seed for reproducibility
(bb = st_bbox(world)) # the world's bounds
random_df = data.frame(
x = runif(n = 10, min = bb[1], max = bb[3]),
y = runif(n = 10, min = bb[2], max = bb[4])
)
random_points = random_df |>
st_as_sf(coords = c("x", "y"), crs = "EPSG:4326") # set coordinates and CRS
p1 <- ggplot(world) +
geom_sf(color = "gray", fill = "white") +
geom_sf(data = random_points, color = "black", shape = 4, lwd = 3) +
coord_sf(datum = NA)
p1
我只想要陆地上的点
world_random = world[random_points, ]
nrow(world_random)
random_joined = st_join(random_points, world["name_long"])
我的尝试:
random_joined$name_long = as.character(random_joined$name_long)
p1 <- ggplot(world) +
geom_sf(color = "gray", fill = "white") +
geom_sf(data = random_joined, aes(fill = name_long), shape = 16) + #, color = "white") +
scale_fill_manual(values = c("blue", "yellow", "red", "orange", "white")) +
coord_sf(datum = NA)
p1
如何以不同的颜色显示指定的国家/地区,并以一种颜色显示
NA
?scale_fill_manual
,而是使用另一种方法来 以编程方式理解值 是 NA
或国家/地区名称。
当您为点设置
shape=16
时,您必须映射到color
aes,因为shape=16
不支持fill
aes并使用scale_color_manual
。如果您想要 NA
的特定颜色,您可以通过 na.value=
的 scale_color_manual
参数来实现。
library(ggplot2)
p1 <- ggplot(world) +
geom_sf(color = "gray", fill = "white") +
# Map on the color aes
geom_sf(data = random_joined, aes(color = name_long), shape = 16) + # , color = "white") +
scale_color_manual(
values = c("blue", "yellow", "red", "orange", "white")
) +
coord_sf(datum = NA)
p1