如何将任何 geom_point 形状添加到 ggplot 图例?

How to add any geom_point shapes to ggplot legend?

我在 ggplot 中制作了一个看起来像这样的热图:

set.seed(1)
n <- 100
df <- data.frame(x= rnorm(n), y= rnorm(n), z= rnorm(n))
df$z[1:20] <- NA
ggplot() +
  geom_point(data= subset(df, !is.na(z)), mapping= aes(x, y, col= z)) +
  geom_point(data= subset(df, is.na(z)), mapping= aes(x, y), col= "black", shape= 4)

这里散点图的点根据 z 中的值改变颜色。此外,我添加了黑色十字 (shape 4) 以可视化 z 中的缺失。我想将与情节中相同的 x 添加到上面的 missing 的图例中。我们该怎么做?

我实际上使用 shape 参数将整个命令放在同一个 geom_point 函数中,然后使用 scale_shape_manual:

手动设置参数
ggplot(df) +
  geom_point(aes(x, y, colour = z, shape = is.na(z))) +
  scale_shape_manual(name = "Missing values", values=c(16, 4))