how to add dashed horizontal line with label in ggplot

17,366

to make the horizontal line dashed and red the following arguments should be included in the geom_hline function call:

linetype = 'dotted', col = 'red'

# Sample Data 

library(tidyverse)
Month= c("Jan","Feb","Mar","Apr","May","Jun")
a = c(11,10,9,8,4,8)

test= data_frame(Month,a) 
test$cum_total <- cumsum(test$a)

test$Month <- factor(test$Month, month.abb)

# ggplot

ggplot(data=test, aes(x=Month, y=cum_total, group=1)) +
  geom_line()+
  geom_point()+
  geom_hline(yintercept=40, linetype='dotted', col = 'red')+
  annotate("text", x = "Feb", y = 40, label = "Previous Level", vjust = -0.5)

enter image description here

Share:
17,366

Related videos on Youtube

Anandapadmanathan
Author by

Anandapadmanathan

Updated on June 04, 2022

Comments

  • Anandapadmanathan
    Anandapadmanathan almost 2 years

    I have plotted a line plot. I have added a horizontal line on the plot. How to take horizontal line red dashed?

    # Sample Data 
    
    library(tidyverse)
    Month= c("Jan","Feb","Mar","Apr","May","Jun")
    a = c(11,10,9,8,4,8)
    
    test= data_frame(Month,a) 
    test$cum_total <- cumsum(test$a)
    
    test$Month <- factor(test$Month, month.abb)
    
    # ggplot
    
    ggplot(data=test, aes(x=Month, y=cum_total, group=1)) +
      geom_line()+
      geom_point()+
      geom_hline(yintercept=40)+
      annotate("text", x = "Feb", y = 40, label = "Previous Level", vjust = -0.5)
    
    • teunbrand
      teunbrand almost 5 years
      Replace your geom_hline() with geom_hline(yintercept = 40, linetype = 2, colour = "red") and it should be dashed and red.
  • Rob
    Rob almost 5 years
    Why should he do that?
  • Kresten
    Kresten almost 5 years
    Updated the answer
  • Rob
    Rob almost 5 years
    I still don't see any explanation as to why he should do that
  • James Hirschorn
    James Hirschorn over 2 years
    I would change it to linetype = 'dashed'.