Ggplot legends when a graph is built from two data frames

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

The following is a simplified example. I came up, but the "Basic Forecast" in the legend is only white. I want to show where the “Basic 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 help would be greatly appreciated.

+6
source share
1 answer

You need to use one of the characters that takes padding (pch = 21:25). Then you need to use override.aes to get the legend. I moved the general data and aes to 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")) 
+3
source

All Articles