0

I would like to start by saying I have read this post and Brian Diggs gave some great help! https://stackoverflow.com/a/9085518/13364594 I am still having trouble getting my geom_segment to stop at a value derived from my data set.

ggplot(Slate_ts,aes (Date, Q))+    
geom_line()+    
geom_segment(data= Slate_ts, xend=as.POSIXct("2019-03-21"),x=as.POSIXct("2019-03-21"),y= -Inf, yend= Q)

Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomSegment, : object 'Q' not found

If I swap the lower most Q for a value of 2 I get a graph:

Slate creek hydrograph

I know I missing something fundamental in the script. Slate_ts data looks like this

  1. Date Q
  2. 2018-10-4 .0018
  3. 2018-10-5 .0027

Thank you r community in advance

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • 1
    As Q is a variable in your df you have to put it inside an `aes()` call. Try `geom_segment(data= Slate_ts, mapping = aes(yend= Q), xend=as.POSIXct("2019-03-21"),x=as.POSIXct("2019-03-21"), y= -Inf)`. – stefan Apr 20 '20 at 18:49
  • I have tried things similar to that, but the graph returns a vertical line with the upper boundary equal in height to the maximum value of Q of the df - from a completely different day. Do I need to specify in the "aes(yend= Q)" script that I want the value of Q on "2019-03-21"? – Nathan Mack Apr 20 '20 at 21:46
  • Please include reproducible data using `dput()`, others can't help you if they can't see the data you have or run your code. See [here for tips on making R questions reproducible and including data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Jan Boyer Apr 20 '20 at 23:17
  • Hi @NathanMack. As far as I got it you want a vertical line at date x = 2019-03-21 reaching up to the the `geom_line`. Simply filter the data used in geom_segement for this date. Try `geom_segment(data= filter(Slate_ts, Date == as.POSIXct("2019-03-21")), mapping = aes(yend= Q, xend = Date, x = Date, y= -Inf))` – stefan Apr 21 '20 at 07:04
  • Thank you! I was missing the concept of filtering by date. – Nathan Mack Apr 21 '20 at 15:35

1 Answers1

0

Using the ggplot2::economics dataset as example data this can be achieved like so. Inside geom_segement simply filter your data for the date where you want to draw the vertical line. Try this:

library(ggplot2)
library(dplyr)

ggplot(economics, aes (date, uempmed))+    
  geom_line() +    
  geom_segment(data = filter(economics, date == as.Date("1995-10-01")), mapping = aes(xend = date, x = date, y = -Inf, yend = uempmed), color = "red")

Created on 2020-04-21 by the reprex package (v0.3.0)

stefan
  • 90,330
  • 6
  • 25
  • 51