Setting values for scale_colour_gradientn in ggplo

2019-08-23 12:25发布

问题:

I'm trying to use scale_colour_gradientn to clearly show neg vs pos values: negative is blue, positive is red. But gradientn seems to ignore my vector of colors, and just makes one big gradient instead of n small gradients. Here's my sample code ...

xx <- -100:100
yy <- xx
fma <- data.frame( xx, yy)
ggplot( fma) +
  geom_point( aes( xx, yy, col=yy)) +
  scale_colour_gradientn(
    colours=c('#0000ff','#0000ff','#ff0000','#ff0000'),
    values=c(  -100,       -1,      1,      100))

How can I convince gradientn to color everything in [-100,-1] blue and everything in [1,100] red?

回答1:

Rather than use scale_color_continuous, I'd make a factor variable that tells what color to color those points and use scale_color_discrete or *_manual. In this example, we use a conditional in the aes so col receives either TRUE or FALSE depending on the value of yy, but if you wanted more possible values, you could use switch or case_when to populate a yy_range variable with the possible color categories.

ggplot(fma) +
    geom_point(aes( xx, yy, col = yy < 0)) +
    scale_color_discrete(c('#0000ff','#ff0000'))



标签: r ggplot2