简体   繁体   中英

Manual scaling of color gradient with scale_color_gradientn() in R

I'm trying to apply a color gradient of three colors (ie, green, black, red) on a line in R.

Sample Code

# Create sample dataframe
df <- data.frame(x = seq(0, 15 , 0.001), 
                 y = seq(0, 15, 0.001))

# Plot data
ggplot(df, aes(x=x, y=y, col = y)) +
  geom_line() +
  scale_color_gradientn(colours = c("green", "black", "red"), 
                        values = rescale(x = c(0, 2, 4), to = c(0,1), from = c(0, 15) ))

在此处输入图像描述

Question

Using the scale_color_gradientn() function, I can apply a color gradient on the line. I would like to use green for values between 0 and 1.5, black for values between 1.5-2.5, and red for 2.5 and up, but I can't seem to grasp the rescale() function. In the example, the color stops at a y-value of 4.

How can I apply the color gradient in the desired way?

Since you provided no value/colour pair for the upper limit of the colour scale, these got interpreted as NAs and became gray. Fixing this should be as easy as providing the upper limit too.

library(ggplot2)
library(scales)
#> Warning: package 'scales' was built under R version 3.6.3

df <- data.frame(x = seq(0, 15 , 0.001), 
                 y = seq(0, 15, 0.001))

# Plot data
ggplot(df, aes(x=x, y=y, col = y)) +
  geom_line() +
  scale_color_gradientn(colours = c("green", "black", "red", "red"), 
                        values = rescale(x = c(0, 2, 4, 15), from = c(0, 15)))

Created on 2020-04-24 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM