1

I have the following minimal example:

df1 <- data.frame(x=1:10, y=rnorm(10))
df2 <- data.frame(x=11:20, y=rnorm(10))
df3 <- data.frame(x=1:10, y=rnorm(10,3,1))
df4 <- data.frame(x=11:20, y=rnorm(10,3,1))

ggplot() + 
  geom_line(data = df1, aes(x = x, y = y, color = "red")) +
  geom_line(data = df2, aes(x = x, y = y, color = "red"), linetype="dashed") +
  geom_line(data = df3, aes(x = x, y = y, color = "blue")) + 
  geom_line(data = df4, aes(x = x, y = y, color = "blue"), linetype="dashed") +
  theme_bw() + 
  theme(legend.title=element_blank()) + 
  theme(legend.text=element_text(size=12)) +
  theme(legend.position = c(.9,.89))

How can I have another legend at the top left of the graph for lines and dashed lines with labels c("Fitted values", Predicted Values")?

I read This, This, and This, but still I can't solve it.

Thanks,

Alirsd
  • 111
  • 9

1 Answers1

2

You can first move the the linetype inside the aes and then create a guide for it.

Then, as moving around legends indipendetly is not easy, we can play with the legend.* theme's setting to get what you want:

library(ggplot2)

ggplot() + 
  geom_line(data = df1, aes(x = x, y = y, 
                            color = "red", 
                            linetype = "Fitted values")) +
  geom_line(data = df2, aes(x = x, y = y, 
                            color = "red", 
                            linetype = "Predicted Values")) +
  geom_line(data = df3, aes(x = x, y = y, 
                            color = "blue", 
                            linetype = "Fitted values")) + 
  geom_line(data = df4, aes(x = x, y = y, 
                            color = "blue", 
                            linetype = "Predicted Values")) +
  scale_linetype_manual(values = c('solid', 'dashed')) +
  scale_colour_manual(values = c('red', 'blue')) +
  theme_bw() + 
  theme(legend.title=element_blank(),
        legend.text=element_text(size=12),
        legend.position = c(.5,.89),
        legend.box = 'horizontal', 
        legend.margin = margin(r = 125, l = 125),
        legend.background = element_rect(fill = NA))

You will have to play with the margin values, and possibily its arg units to have a consistent and nice result.

GGamba
  • 13,140
  • 3
  • 38
  • 47
  • Thank you so much. It works for me, and it was much easier than the solutions that others mentioned in the [link](https://stackoverflow.com/questions/13143894/how-do-i-position-two-legends-independently-in-ggplot) . Keep doing great :) – Alirsd Jun 20 '17 at 21:37