2

Does anyone know how to set different colours above and under a particular treshold when using geom_line. The Problem is that this treshold might not go exactly through one of those points from the data. So if there is the case that one point is above the treshold and the next is under the treshold the connecting line should change the colour at the level of the treshold. Here is an example:

set.seed(10)   
d3 = data.frame("time" = seq(from = as.POSIXct("2015-01-02 02:00", format="%Y-%m-%d %H:%M"),
                           to = as.POSIXct("2015-01-07 01:00", format="%Y-%m-%d %H:%M"),
                           by = "hour"), "exchange rate" = round(runif(120, min = 0.25, max = 0.55 ),2))

# for geom_point a good solution is to cut the data
d3$col = cut(d3$exchange.rate, breaks = c(0.25,0.4,0.55))
library(ggplot2)
library(scales)
ggplot(d3)+
geom_line(aes(time, exchange.rate, col = col))+
scale_y_continuous(name = "Exchange Rate", limits = c(0.2,0.6))+
scale_x_datetime(name = "Hour", labels = date_format("%H:%M"),
               date_breaks = "12 hours", expand = c(0,0) )+
geom_hline(yintercept = 0.4)+
geom_rect(aes(xmin = as.POSIXct("2015-01-02 02:00"), xmax =    as.POSIXct("2015-01-07 02:00"), ymin = -Inf, ymax = 0.4),
        fill = "lightblue", alpha = 0.008)+
theme_bw()

It does not make sense to cut the data, as it will create two lines independent of each other. So I tried:

ggplot(d3)+
geom_line(aes(time, exchange.rate), col = ifelse(d3$exchange.rate>0.4,"turquoise","pink"))+
scale_y_continuous(name = "Exchange Rate", limits = c(0.2,0.6))+
scale_x_datetime(name = "Hour", labels = date_format("%H:%M"),
               date_breaks = "12 hours", expand = c(0,0) )+
geom_hline(yintercept = 0.4)+
geom_rect(aes(xmin = as.POSIXct("2015-01-02 02:00"), xmax = as.POSIXct("2015-01-07 02:00"), ymin = -Inf, ymax = 0.4),
        fill = "lightblue", alpha = 0.008)+
theme_bw()

This sets the treshold for the points but not for the lines. Any suggestions?

Henrik
  • 65,555
  • 14
  • 143
  • 159
  • Related question with other ways to interpolate: [How to fill geom_polygon with different colors above and below y = 0?](https://stackoverflow.com/questions/27135962/how-to-fill-geom-polygon-with-different-colors-above-and-below-y-0) – Henrik Feb 10 '18 at 10:50

0 Answers0