+3 votes
in Programming Languages by (60.0k 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

+1 vote
by (354k points)
selected by
 
Best answer

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

+3 votes
1 answer
+1 vote
1 answer
+5 votes
1 answer
asked Sep 16, 2021 in Programming Languages by praveen (72.7k points)
+1 vote
1 answer
+1 vote
1 answer

...