Home > Software design >  How to apply a continous color ramp to a straight line in ggplot2?
How to apply a continous color ramp to a straight line in ggplot2?

Time:02-23

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

CodePudding user response:

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

CodePudding user response:

As @stefan already suggests in the comments we could use geom_link2 from ggforce package, here is an example:

library(tidyverse)
library(ggforce)

ggplot(mtcars, aes(x=cyl, y=mpg))  
  geom_point() 
  geom_link2(aes(x = 5, y = mpg, colour = mpg), size=2) 
  scale_color_gradient2(midpoint=mid, low="green", mid="white",
                          high="red")

enter image description here

  • Related