Using geom_segment to connect a line to the y-axis

Viewed 278

I want to use geom_segment to make a line intercept the y-axis, the problem I am experiencing becomes readily apparent. Starting off with sample data:

dat <- data.frame(Yaxis = c(100,200,300,400,500,600,700,800), Year = c(2012,2013,2014,2015,2016,2017,2018,2019)) 

p <- ggplot(data=dat, aes(x=Year)) + geom_line(aes(y=Yaxis))

enter image description here

and adding a geom_segment layer produces:

p + geom_segment(aes(x=0,xend=2012,y=75,yend=100))

enter image description here

my attempts to amend this haven't worked out so far:

p + geom_segment(aes(x=0,xend=2012,y=75,yend=100)) + scale_x_continuous(expand= c(0,0), breaks = c(2012,2013,2014,2015,2016,2017,2018,2019))

For reference, here is a crude drawing of what I intend the graph to look like: enter image description here

Thanks to @Sathish 's answer, I was able to create the graph I intended using

ggplot(data=dat, aes(x=as.Date(paste(Year,'-01-01', sep=""), "%Y-%m-%d"), y=Yaxis)) + 
  geom_line() + 
  geom_segment(aes(
               x=as.Date("2011-01-01", "%Y-%m-%d"),
               xend=as.Date("2012-01-01", "%Y-%m-%d"),
               y=75, 
               yend=100), color = "red") +
  scale_x_date(expand = c(0,0))

enter image description here

1 Answers

Convert Year column to Date class.

library('ggplot2')
ggplot(data=dat, aes(x=as.Date(paste(Year, '-01-01', sep = ""), "%Y-%m-%d"), y=Yaxis)) + 
  geom_line() +
  geom_segment(aes(x=as.Date("2012-01-01", "%Y-%m-%d"),xend=as.Date("2020-01-01", "%Y-%m-%d"),y=75,yend=100), color = "red") +
  xlab(label = "Year")

enter image description here

Related