Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 - How do I specify out of bounds values' colour

Tags:

r

ggplot2

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 = " ")) 
like image 795
HoaxKey Avatar asked May 14 '14 11:05

HoaxKey


People also ask

How do I assign a color to a variable in R?

In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.

What is the difference between fill and color in R?

The color attribute is only used for point, line and scatter chart, fill is generally used for bar, column chart, etc. Color adds color to the border to plot whereas fill is to color inside bar/column, etc.


1 Answers

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) 
like image 152
Stefan Seemayer Avatar answered Sep 20 '22 23:09

Stefan Seemayer