Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

r - Create ggplot2 legend for multiple datasets

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

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One solution is to create color vector and pass it to scale_color_manual.

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)
# rbind both datasets
# OP tried to use rbind.data.frame here
plotData <- rbind(xx, yy)

# Create color vector
library(RColorBrewer)
# Extract 3 colors from brewer Set1 palette
colorData <- brewer.pal(length(unique(plotData$observation)), "Set1")
# Replace first color first wanted grey
colorData[1] <- "grey60"

# Plot data
library(ggplot2)
ggplot(plotData, aes(x, y, colour = observation)) + 
    geom_point(size = 5)+
    scale_color_manual(values = colorData, name = "ltitle")

                                     enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...