在ggplot2中设置scale_colour_gradientn的值 [英] Setting values for scale_colour_gradientn in ggplot2
问题描述
我正在尝试使用scale_colour_gradientn清楚地显示负值与pos值:负数是蓝色,正数是红色.但是,gradientn似乎忽略了我的颜色矢量,只创建了一个大渐变而不是n个小渐变.这是我的示例代码...
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))
我如何说服渐变色将[-100,-1]蓝色的所有内容和[1,100]红色的所有内容着色?
How can I convince gradientn to color everything in [-100,-1] blue and everything in [1,100] red?
推荐答案
我会使用 factor
变量,而不是使用 scale_color_continuous
来告诉这些颜色为哪种颜色着色点并使用 scale_color_discrete
或 * _ manual
.在此示例中,我们在 aes
中使用条件,因此 col
会根据值接收 TRUE
或 FALSE
的 yy
,但是如果您想要更多可能的值,则可以使用 switch
或 case_when
填充 yy_range
变量以及可能的颜色类别.
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'))
这篇关于在ggplot2中设置scale_colour_gradientn的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!