在geom_line的特定阈值下更改颜色

时间:2018-02-10 01:13:40

标签: r ggplot2 colors

使用geom_line时,是否有人知道如何在特定阈值之上和之下设置不同的颜色。问题是此阈值可能不会完全通过数据中的其中一个点。因此,如果存在一个点高于阈值并且下一个点低于阈值的情况,则连接线应该改变阈值水平的颜色。这是一个例子:

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()

切割数据没有意义,因为它会创建两条彼此独立的线。所以我试过了:

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()

设置点的阈值,但不设置线的阈值。有什么建议吗?

0 个答案:

没有答案