Pregunta

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 = " "))
¿Fue útil?

Solución

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)

Otros consejos

Try changing geom_tile to below:

  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:

geom_tile(aes(fill = ifelse(value<0.6,0.6,
                            ifelse(value>1,1,
                                   value))))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top