James_S
James_S

Reputation: 19

Changing linetype within timeseries ggplot2

I have a time series dataset of stream flow and water temperature that I’d like to plot and highlight when temperature exceeds a certain threshold. Ideally, I’d do this by changing linetype whenever the temperature value exceeds this threshold. However, I can’t figure out how to get ggplot to change linetypes multiple times in the data set, without creating multiple lines. Below is a dummy dataset.

#date values
date<-seq(as.Date("2019-01-01"), as.Date("2019-01-30"), "days")
#set arbitrary values for variables
set.seed(10)
val1<-rnorm(30, mean = 10)
val2<-rnorm(30, mean = 50)
df<-data.frame(date, val1, val2)

#add a threshold grouping layer to plot with
df$group<-ifelse(df$val2 <= 50, "One","Two")

What I’d like to do is to use a solid line when plotting between “One” and dashed line when plotting to “Two” – essentially connecting points by color in the plot below.

ggplot(df, aes(date, val1))+
  geom_line()+
  geom_point(aes(col = group))

Single time series with colored points noting threshold

However, when I add a linetype aesthetic, ggplot separates the data into two groups and plots two lines:

#what happens when I plot by linetype
ggplot(df, aes(date, val1))+
  geom_line(aes(linetype = group))+
  geom_point(aes(col = group))

Results when I use linetype as aesthetic

I might be able to figure out a way to hack multiple datasets and plot them together to accomplish this, but I’m going to have several groups of data plotted in faceted plots, so this is not ideal.

Other examples I’ve found, such as this only work because the clean break in the time series data. Likewise these two aren’t going back and forth, so is not of much use for my application.

Upvotes: 0

Views: 726

Answers (1)

Jon Spring
Jon Spring

Reputation: 67020

Does this do what you want?

ggplot(df, aes(date, val1))+
  geom_segment(aes(xend = lead(date),
                   yend = lead(val1),
                   lty = lead(group))) +
  geom_point(aes(col = group))

enter image description here

Upvotes: 3

Related Questions