I am trying to display background data in grey in a ggplot with legend automatically. My aim is to either include the grey datapoints in the legend, or to make a second legend with a manual title. However I fail at doing any of the two. My data is in long format.
require(ggplot2)
xx<-data.frame(observation="all cats",x=1:2,y=1:2)
yy<-data.frame(observation=c("red cats","blue cats"),x=3:4,y=3:4)
g<-ggplot() +
geom_point(aes(x,y, colour=factor(observation)), colour="grey60", size=5, data=xx) +
geom_point(aes(x,y, colour=factor(observation)), size=5, data=yy) +
scale_color_discrete(name = "ltitle")
g
I tried to merge the data.frames with rbind.data.frame
, which produces a nice legend, but then I am not able to colour the background data in grey and keep ggplot colours at the same time.
I also realized that this solves the problem:
g<-ggplot(aes(x,y, colour=factor(observation)), colour="grey60", data=xx) +
geom_point(size=5) +
geom_point(aes(x,y, colour=factor(observation)), size=5, data=yy) +
scale_color_discrete(name = "ltitle")
g
however I can't do this, because I'm using a function which creates a complicated empty plot before, in which I then add the geom_points
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…