Jinesh Patel Jinesh Patel - 1 year ago 174
R Question

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

Any assistance will be greatly appreciated.

Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download