Draw Y axis line with segments of different colors

Viewed 148

Normally you can change the color of the entire axis line with:

theme ( axis.line.y = element_line(color = "gray", size = 1) )

However, I want to draw a Y-axis where different parts have different colors. For example, a blue line below 0, and red above zero. A small example, where the axis has been "painted" manually:

df <- data.frame(x = 1:8, y = -3:4)

ggplot(df, aes(x, y)) +
    geom_point()

enter image description here

Thanks a lot!

EDIT: The answer by Allan Cameron is correct but doesn´t work for me since I´ve got a time series plot where my x-axis is in time format (POSIXct). His post gave me some an idea how this works and I feel like I´ve got it working with some tricks. Here is how I do it, it can be adapted for different cases / ranges. Need package "lubridate" to add / substract times.

  1. Get min and max of my x-axis:

minX <- min(myData$Timestamp)

maxX <- max(myData$Timestamp)

  1. Set limit:

lim <- as.POSIXct(c(minX -minutes (5), maxX), origin = "1970-01-01")

  1. coord_cartesian like this:

+ coord_cartesian(xlim=c(minX - minutes(5), maxX),c(60,100), expand = FALSE)

  1. Draw line:

+ geom_segment(aes(x = minX - minutes(5), y = 60, xend = minX - minutes(5), yend = 70), size = 1, color = "red"

Keep in mind this is for my use case. I may need to adjust this (and edit this post more)

1 Answers

If you want two colours, you need two lines. You cannot have two axis lines, so you need to draw the lines as segments, as in the following reprex:

library(ggplot2)

df <- data.frame(x = 0:10, y = 0:10)

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_segment(aes(x = 0, y = 0, xend = 0, yend = 2), size = 2, color = "red") +
  geom_segment(aes(x = 0, y = 2, xend = 0, yend = 10), size = 2, color = "blue") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  theme(axis.line.y = element_blank(),
        axis.line.x = element_line())

Created on 2020-08-07 by the reprex package (v0.3.0)

Related