[英]R ggplot2 - How do I specify out of bounds values' colour
In the plot generated by the following code I would like to alter the colours so that all values < 0.6 are the same as the "low" colour and all values greater than 1 are the "high" colour. 在下面的代码生成的图中,我想更改颜色,以使所有<0.6的值都与“低”颜色相同,而所有大于1的值都为“高”颜色。
As is stands the colour gradient stretches across the entire numeric range of the data. 照原样,颜色渐变会扩展到数据的整个数字范围。 I have tried adding limits but that makes all out of bounds value the same colour as NA values, which is not what I want because I need missing NA values to clearly stick out and not look the same colour as out of bounds values <0.6.
我尝试添加限制,但是这会使所有超出范围的值与NA值具有相同的颜色,这不是我想要的,因为我需要缺少NA值才能清楚地突出显示,并且看起来与<0.6的超出范围的颜色不一样。
I'm convinced that the answer is with the oob, breaks arguments but have had no success getting it to work. 我坚信答案是oob,打破了争论,但未能成功。
library(ggplot2)
a = rnorm(17*17, 0.733,0.21)
qcMat = matrix(a, ncol = 17)
qcMat[qcMat> 1] = 1
#qcMat contains values between 0 and 1 and some NAs
m = melt(t(qcMat))
m$Var2 <- with(m,factor(Var2, levels = rev(sort(unique(Var2)))))
ggplot(m, aes(as.factor(Var1), Var2, group=Var2)) +
geom_tile(aes(fill = value)) +
geom_text(aes(fill = m$value, label = round(m$value, 2))) +
scale_fill_gradient(low = "red", high = "green") +
xlab("") + ylab("") + ggtitle(paste("biscuit:", biscuit_id, "- QC", sep = " "))
As you said youself, you want the oob
argument in the scale_fill_gradient
. 正如您自己说的那样,您需要在
scale_fill_gradient
使用oob
参数。 To clamp values, you can use squish from the scales package ( scales
is installed when ggplot2
is installed): 为了钳位值,你可以使用嘎吱从鳞包 (
scales
当安装ggplot2
安装):
library(scales)
and later 然后
scale_fill_gradient(low = "red", high = "green", limits=c(0.6, 1), oob=squish)
Try changing geom_tile
to below: 尝试将
geom_tile
更改为以下内容:
geom_tile(aes(fill = ifelse(value<0.6,min(m$value,na.rm=TRUE),
ifelse(value>1,max(m$value,na.rm=TRUE),
value))))
EDIT: Then don't use min max, so we will get 0.6-1 range: 编辑:然后不要使用最小最大,所以我们将得到0.6-1范围:
geom_tile(aes(fill = ifelse(value<0.6,0.6,
ifelse(value>1,1,
value))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.