使用scale_…_manual将自定义图例添加到具有两个geom_point层的ggplot中

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

例如,我有两个数据集,第一个数据集包含计算点,第二个数据集包含网格坐标。我想使用ggplot绘制它们,并且希望图例如下所示:

enter image description here

数据

df1<- data.frame(lon=c(21:70), lat=c(64:113), tem=c(12:61)) # computation points data
df2<- data.frame(grd.lon=seq(21,70,3.5),grd.lat=seq(12,61, 3.5))  # grid points data
 library(ggplot2)
ggplot()+geom_point(data=df1, aes(x=lon,y=lat), color="black", shape=20, size=3)+
            geom_point(data=df2, aes(x=grd.lon, y=grd.lat), colour="red", shape=3)

我见过类似的问题,但没有一个对我有真正的帮助我还尝试通过添加scale_color_manual和scale_shape_manaul手动绘制图例,但仍然无法正常工作。任何帮助请

r ggplot2 point
1个回答
5
投票

将您的df绑定到一个,就像这样:

df3 <- list("computation point" = df1, "grid points" = df2) %>% 
  bind_rows(.id = "df")

比将变量映射到美学。 ggplot2然后将自动添加图例,可以使用scale _..._ manual对其进行调整:

ggplot(df3, aes(shape = df, color = df)) +
  geom_point(aes(x=lon,y=lat), size=3)+
  geom_point(aes(x=grd.lon, y=grd.lat)) +
  scale_shape_manual(values = c(20, 3)) +
  scale_color_manual(values = c("black", "red")) +
  labs(shape = NULL, color = NULL)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.