I would like to use my own specific color in my image plot. I am very new in ggplot2 so had a look at its manual from here - the old link does not exist and now is here - and tried to repeat some of the stuff; but I couldn't figure out how to supply my colorbar as I did for the graphics plot.
library(reshape2)
library(ggplot2)
#my specific color list
mycol <- vector(length=512, mode = "numeric")
for (k in 1:256) mycol[k] <- rgb(255, k - 1, k - 1, maxColorValue=255)
for (k in 257:512) mycol[k] <- rgb(511 - (k - 1), 511 - (k - 1), 255, maxColorValue=255)
mycol <- rev(mycol)
ncolors <- length(mycol)
# graphics plot
par(mar = c(5, 13, 1, 6))
image(1:ncol(volcano), 1:nrow(volcano), t(volcano), zlim = c(0, ncolors), col=mycol, axes=FALSE, main="W Matrix", sub = "", xlab= "Components", ylab="Genes")
axis(2, at=1:nrow(volcano), labels=row.names(volcano), adj= 0.5, tick=FALSE, las = 1, cex.axis=0.25, font.axis=1, line=-1)
axis(1, at=1:ncol(volcano), labels=colnames(volcano), adj= 0.5, tick=FALSE,las = 3, cex=1, cex.axis=0.5, font.axis=1, line=-1)
# ggplot2
library(reshape2)
library(ggplot2)
library(ez)
ggplot(melt(volcano), aes(x=Var1, y=Var2, fill=value)) + geom_tile() + scale_color_gradient2(low = muted("red"), mid = "white", high = muted("blue"), midpoint = 0, space = "rgb", guide = "colourbar") # the code does not really use my color bar
Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0
Just to clarify @Didzis' answer, which works but may not produce the gradient you're looking for...
'midpoint' refers to the numerical value at which you want the color specified by 'mid' to appear. So, instead of setting the 'midpoint' argument to 256 (which falls outside the range of value
, which is the vector you're coloring by), it's wise to set it to a value somewhere in the middle of the range of values you are coloring by, otherwise you aren't using the entire gradient you specified with 'low' and 'high', which defeats the purpose of scale_color_gradient2
. The exact value depends on what you are trying to communicate visually, but usually the mean or median is used. Here, I edited @Didzis' code with 'midpoint' set to the median of value
v <- melt(volcano)
ggplot(v, aes(x=Var1, y=Var2, fill=value)) +
geom_tile() +
scale_fill_gradient2(low = "#0000FF", mid = "#FFFFFF", high ="#FF0000",
midpoint = median(v$value), space = "rgb", guide = "colourbar")
This gives a plot with a much wider gradient:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With