+2 votes
in Programming Languages by (8.5k points)

I am using the following code to add vertical lines to the plot. How can I add legend for the vertical lines? 

library(ggplot2)

x <- c(1:10)

y <-sin(x)

df <-data.frame(xvals=x, yvals=y)

p1 <- ggplot(df,aes(x,y)) +

  geom_line() +

  scale_x_continuous(limits = c(0, 10), breaks = seq(0, 10, 1), minor_breaks = seq(0, 10, 0.2)) +

  scale_y_continuous(limits = c(-1, 1), breaks = seq(-1, 1, 0.5), minor_breaks = seq(-1, 1, 0.1)) +

  geom_vline(aes(xintercept=3), color="red", linetype="dashed", size=1) +

  geom_vline(aes(xintercept=5), color="blue", linetype="dashed", size=1)

1 Answer

0 votes
by (32.8k points)

You need to put color inside the aes() of geom_vline() and then add scale_color_manual() to set the desired color for the vertical lines.

Here is an example:

library(ggplot2)
x <- c(1:10)
y <-sin(x)
df <-data.frame(xvals=x, yvals=y)
p1 <- ggplot(df,aes(x,y)) +
  geom_line() +
  scale_x_continuous(limits = c(0, 10), breaks = seq(0, 10, 1), minor_breaks = seq(0, 10, 0.2)) +
  scale_y_continuous(limits = c(-1, 1), breaks = seq(-1, 1, 0.5), minor_breaks = seq(-1, 1, 0.1)) +
  geom_vline(aes(xintercept=3, color="x_3"), linetype="dashed", size=1) +
  geom_vline(aes(xintercept=5, color="x_5"), linetype="dashed", size=1) +
  scale_color_manual(values = c("x_3" = "blue", "x_5" = "red")) +

  theme(panel.grid.major = element_line(colour="grey", size=0.5), panel.grid.minor = element_line(colour="white", size=0.5), legend.title=element_blank())

The above code will generate the following plot:

Legend for vline in ggplot

Related questions

...