Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - ggplot legends when plot is built from two data frames

I have data coming from two different data frames. I am trying to create legend for each data frame. I know I can combine the data frame and do it, but because of my data source it makes the most sense to plot from two different data frames.

Please find the simplified example below. I have gotten close but the 'Main Forecast' in the legend is only white color. I want to show where 'Main Forecast' is red on the outside and white on the inside.

x = seq(1,10, 1)
y = seq(10,100, 10)

df  = data.frame(x=x, y=y)
df2 = data.frame(x=5, y=50)

p = ggplot(data=df) + 
  geom_point(data=df,aes(x=x, y=y, color="Weekly Forecast"), fill="red", size=5, shape=16)  + 
  geom_line(data=df,aes(x=x, y=y), color="red", size=1)  + 
  geom_point(data=df2, aes(x=x, y=y, color="Main Forecast"), size=2, shape=16)  +
  scale_color_manual("Legend Title", breaks=c("Weekly Forecast", "Main Forecast"), values = c("white","red"))
p

Any assistance will be greatly appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to use one of the symbols that takes a fill (pch = 21:25). You then need to use override.aes to get the legend right. I've moved shared data and aes into the ggplot command.

ggplot(data=df, aes(x=x, y=y)) + 
  geom_point(aes(color="Weekly Forecast"), shape=16, size = 5)  + 
  geom_line(color="red", size=1)  + 
  geom_point(data=df2, aes(color="Main Forecast"), shape=21, fill = "white", size = 5)  +
  scale_color_manual("Legend Title", limits=c("Weekly Forecast", "Main Forecast"), values = c("red","red")) +
  guides(colour = guide_legend(override.aes = list(pch = c(16, 21), fill = c("red", "white"))))

This can also be done without override.aes:

ggplot(data=df, aes(x=x, y=y)) + 
  geom_line(aes(color="Main Forecast"), size=1)  + 
  geom_point(aes(color="Weekly Forecast", fill="Weekly Forecast"), shape=21, size = 5)  +
  geom_point(data=df2, aes(color="Main Forecast", fill="Main Forecast"), shape=21, size = 5)  +
  scale_color_manual(name="", values = c("red","red")) +
  scale_fill_manual(name="", values=c("white","red"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...