使用ggplot2对列进行颜色并排除 NA

问题描述 投票:0回答:1

我想为一列着色,但请使用

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
或国家/地区名称。

r ggplot2 join colors na
1个回答
0
投票

当您为点设置

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

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.