rggplot2geom-hlinegeom-vlinegeom-segment

How to apply a continous color ramp to a straight line in ggplot2?


I have would like to apply a continous color ramp to a vertical line in ggplot2. My plot is below. I have applied the continous color ramp to the geom_line() element, while the horizontal lines represent the limits of the range covered by the color ramp and are appropriately colored. I would like the vertical line on the left side to show the full range of the color ramp between the two horizontal lines.

I tried geom_segment(aes(color=dwsTempOutC)) (dwsTempOutC is my y axis variable) but as you can see in the image it only applied a single color to the line.

I imagine I could achieve a continous color ramp by generating a series of short line segments and applying a discrete color from the ramp to each, but I'm hoping there is a less hacky way to do it.

enter image description here


Solution

  • The issue is that when using geom_segment then, well, there is only one segment. However, besides ggforce::geom_link you could achieve the same result using geom_line:

    Using some fake data:

    df <- data.frame(
      x = seq(0, 2 * pi, length.out = 100),
      y = sin(seq(0, 2 * pi, length.out = 100))
    )
    
    library(ggplot2)
    
    ggplot(df, aes(x, y, color = y)) +
      geom_line() +
      geom_line(data = data.frame(x = -.5, y = seq(-1, 1, length.out = 100))) +
      scale_color_viridis_c()