1

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

ia200
  • 255
  • 1
  • 9
  • 1
    It would be eaiser to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Feb 22 '22 at 19:25
  • This said: Basically one option to achieve your desired result would be `ggforce::geom_link` – stefan Feb 22 '22 at 19:26
  • `geom_link` seems like it would get the job done but does ggplot2 not a have a way to do this internally? I would prefer not to use additional packages unless ggplot2 is unable to achieve this. – ia200 Feb 22 '22 at 19:40

2 Answers2

3

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Thanks! Both solutions work but the geom_line() approach is great because it doesn't require any other packages. – ia200 Feb 22 '22 at 19:58
2

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

TarJae
  • 72,363
  • 6
  • 19
  • 66