Mahmoud
Mahmoud

Reputation: 401

R - geom_point - grouping to be used for legend

I have two geom_point commands applied to different data frames and would like to have a legend to specify them. However, I am not sure how to group them right for the legend. I appreciate it if you can take a look at the simple example below and help me figure out why no legend appears on the figure. Thanks!

df1=data.table(x1=c(-1,0,1), y1=c(-1,0,1))
df2=data.table(x2=c(-1,0,1), y2=c(-2,0,2))
ggplot()+
geom_point(data=df1, aes(x=x1, y=y1), color='red',  group=1) +
geom_point(data=df2, aes(x=x2, y=y2), color='blue', group=2) +
xlab("X Label")+ylab("Y Label") +
scale_colour_manual(name = "My Legend", 
                 values = group,
                 labels = c("database1", "database2"))

Upvotes: 0

Views: 224

Answers (1)

r2evans
r2evans

Reputation: 161110

As suggested, ggplot2 likes a "tidy" way of dealing with data. In this case, it involves combining the data with an additional variable to differentiate the groups:

colnames(df2) <- c("x1","y1")
df <- rbind(transform(df1, grp='red'), transform(df2, grp='blue'))

ggplot()+
geom_point(data=df, aes(x=x1, y=y1, color=grp),  group=1) +
xlab("X Label")+ylab("Y Label") +
scale_color_identity(guide="legend")

I used scale_color_identity for simplicity here, but it isn't hard to use where you started going with scale_colour_manual and relabeling them.

enter image description here

Upvotes: 1

Related Questions