How to add legened to geom_vline?

159 views Asked by At

I have a dataframe (df_new) that looks something like this:

date<- c("2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05")
A <- c(23, 41, 32, 58, 26)
B <- c(10, 20, 30, 40, 50)
  
df_new <- data.frame(date, A, B)
df_new$date <- as.Date(df_new$date)

I am using the following code to plot values A and B.

ggplot(data = df_new, aes(x = date)) + 
  geom_line(aes(y = A, colour = "Value A")) + 
  geom_line(aes(y = B, colour = "Value B"))+
  labs(title = 'A & B Distribution',
       x = '',
       y = 'Value Count',
       color = " ") +
  theme_bw() +
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x)))+
  geom_vline(xintercept = as.numeric(as.Date("2020-01-03")), linetype=4)+
  theme(text=element_text(size=13),panel.spacing.x=unit(0.6, "lines"),
        panel.spacing.y=unit(1, "lines"))

It is giving me the plot as desired enter image description here except that I would like to add a legend of geom_vline under Value B where I have manually drawn a black line.

Any guidance please?

1

There are 1 answers

4
Quinten On BEST ANSWER

You can manually set a legend with color using scale_color_manual. You name the color of vline black which you can assign as a value in the legend by "black"="black". This can be manually changed to whatever you want. You can use the following code:

library(tidyverse)
library(scales)
ggplot(data = df_new, aes(x = date)) + 
  geom_line(aes(y = A, colour = "Value A")) + 
  geom_line(aes(y = B, colour = "Value B"))+
  labs(title = 'A & B Distribution',
       x = '',
       y = 'Value Count',
       color = " ") +
  theme_bw() +
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x)))+
  geom_vline(xintercept = as.numeric(as.Date("2020-01-03")), linetype=4, color = "black")+
  theme(text=element_text(size=13),panel.spacing.x=unit(0.6, "lines"),
        panel.spacing.y=unit(1, "lines")) +
  scale_color_manual(name = "Legend", values = c("Value A" = "red", "Value B" = "blue", "black" = "black"))

Output:

enter image description here