line color according to values on Y axis

46 views
Skip to first unread message

Dr Eberhard Lisse

unread,
Aug 23, 2021, 7:50:09 PM8/23/21
to ggp...@googlegroups.com
Hi,

at the moment I am using

geom_line() +
scale_colour_gradient(low = "green", high = "red")

to color the line depending on value (on the Y Axis).

I can't figure out how to have values from 0-49 (low (green)), 50-99
(mid (yellow)), and 100 and above (high red) color the line in those
three different colors accordingly.

Gradient is not required but would be cool.

Any idea or pointer to where to read that up?

greetings, el
--
To email me replace 'nospam' with 'el'

Ron Crump

unread,
Aug 24, 2021, 3:49:32 AM8/24/21
to ggp...@googlegroups.com
Hi,

> at the moment I am using
>
>     geom_line() +
>     scale_colour_gradient(low = "green", high = "red")
>
> to color the line depending on value (on the Y Axis).
>
> I can't figure out how to have values from 0-49 (low (green)), 50-99
> (mid (yellow)), and 100 and above (high red) color the line in those
> three different colors accordingly.
>
> Gradient is not required but would be cool.

Without a gradient, I'd use cut to convert my
values into a factor and then scale_colour_manual to
set the colours.

With a gradient, I suggest scale_colour_gradient2
or playing with scale_colour_gradientn which might help
you get more yellow values and a gradient.

TBL<-tibble(x=0:150,y=0:150)
TBL <- TBL %>%
mutate(yf = cut(y, breaks = c(-Inf, 49 , 99, Inf),
labels = c('Low', 'Medium', 'High')))

p1 <- ggplot(data = TBL, aes(x = x, y = y, colour = yf)) +
geom_line() +
scale_colour_manual(values = c('red', 'yellow', 'green'))

p2 <- ggplot(data = TBL, aes(x = x, y = y, colour = y)) +
geom_line() +
scale_colour_gradient2(low = 'red', mid = 'yellow',
high = 'green', midpoint = mean(0:150)


Hope this helps,
Ron.

Dr Eberhard Lisse

unread,
Aug 24, 2021, 3:58:15 AM8/24/21
to ggp...@googlegroups.com
Thanks,

long weekend coming up :-)-O

el
On 24/08/2021 09:49, 'Ron Crump' via ggplot2 wrote:
[...]
> Without a gradient, I'd use cut to convert my
> values into a factor and then scale_colour_manual to
> set the colours.
>
> With a gradient, I suggest scale_colour_gradient2
> or playing with scale_colour_gradientn which might help
> you get more yellow values and a gradient.
>
> TBL<-tibble(x=0:150,y=0:150)
> TBL <- TBL %>%
>     mutate(yf = cut(y, breaks = c(-Inf, 49 , 99, Inf),
>                        labels = c('Low', 'Medium', 'High')))
>
> p1 <- ggplot(data = TBL, aes(x = x, y = y, colour = yf)) +
>     geom_line() +
>     scale_colour_manual(values = c('red', 'yellow', 'green'))
>
> p2 <- ggplot(data = TBL, aes(x = x, y = y, colour = y)) +
>     geom_line() +
>     scale_colour_gradient2(low = 'red', mid = 'yellow',
>                            high = 'green', midpoint = mean(0:150)
>
>
> Hope this helps,
> Ron.
>


Reply all
Reply to author
Forward
0 new messages