Milaa
Milaa

Reputation: 419

Add a custom legend to a ggplot with two geom_point layers using scale_..._manual

I have e.g two data sets first set contains the computation points and the second contains the grid coordinates. I want to plot them using ggplot and I want the legend to be as shown below:

enter image description here

The data

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)

I have seen similar questions but none of them really helped me I tried also to plot the legend manually by add scale_color_manual and scale_shape_manaul, but still didn't work. Any help please

Upvotes: 5

Views: 423

Answers (1)

stefan
stefan

Reputation: 124558

Bind your df's in one, like so:

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

Than map variables to aesthetics. ggplot2 will then automatically add a legend, which can be adjusted using 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

Upvotes: 5

Related Questions