Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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.

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.

I'm convinced that the answer is with the oob, breaks arguments but have had no success getting it to work.

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 = " "))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you said youself, you want the oob argument in the scale_fill_gradient. To clamp values, you can use squish from the scales package (scales is installed when ggplot2 is installed):

library(scales)

and later

scale_fill_gradient(low = "red", high = "green", limits=c(0.6, 1), oob=squish)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...