ggplot legends when plot is built from two data frames

荒凉一梦 提交于 2019-12-19 06:01:31

问题


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.


回答1:


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"))


来源:https://stackoverflow.com/questions/38907371/ggplot-legends-when-plot-is-built-from-two-data-frames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!