Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot line in different colors above versus below zero

Tags:

plot

r

colors

I'd like the plotted line to be blue for values above zero and red for values below zero.

Sample data:

dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2)
abline(h = 0, col = "grey")

Result:

image of resulting plot

Expected result:

image of expected resulting plot

I do not want to use ggplot2 and would prefer a solution in base R.


2 Answers

Following this answer [as @Sonny suggested in the comment], you can do this using clip:

dat <- data.frame(u = 1:10,
                  v = c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
plot(dat, type = "l", lwd = 2, col = "blue")
clip(x1 = min(dat$u),
     x2 = max(dat$u),
     y1 = min(dat$v),
     y2 = 0)
lines(dat, lwd = 2, col = "red")
abline(h = 0, col = "grey")

Created on 2019-03-24 by the reprex package (v0.2.1)

like image 97
yarnabrina Avatar answered Mar 01 '26 19:03

yarnabrina


I am now using clplot() from the plotrix package:

dat <- data.frame(1:10, c(-2, -3, -1, 1, 2, 1, -2, 2, 4, 3))
library(plotrix)
clplot(dat[, 1], dat[, 2], levels = c(0), cols = c("red", "blue"), lwd = 2)

enter image description here


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!