r - easiest way to discretize continuous scales for ggplot2 color scales? -
suppose have plot:
ggplot(iris) + geom_point(aes(x=sepal.width, y=sepal.length, colour=sepal.length)) + scale_colour_gradient()
what correct way discretize color scale, plot shown below accepted answer here (gradient breaks in ggplot stat_bin2d plot)?
ggplot correctly recognizes discrete values , uses discrete scales these, question if have continuous data , want discrete colour bar (with each square corresponding value, , squares colored in gradient still), best way it? should discretizing/binning happen outside of ggplot , put in dataframe separate discrete-valued column, or there way within ggplot? example of i'm looking similar scale shown here:
except i'm plotting scatter plot , not geom_tile
/heatmap.
thanks.
the solution complicated, because want discrete scale. otherwise use round
.
library(ggplot2) bincol <- function(x,low,medium,high) { breaks <- function(x) pretty(range(x), n = nclass.sturges(x), min.n = 1) colfunc <- colorramppalette(c(low, medium, high)) binned <- cut(x,breaks(x)) res <- colfunc(length(unique(binned)))[as.integer(binned)] names(res) <- as.character(binned) res } labels <- unique(names(bincol(iris$sepal.length,"blue","yellow","red"))) breaks <- unique(bincol(iris$sepal.length,"blue","yellow","red")) breaks <- breaks[order(labels,decreasing = true)] labels <- labels[order(labels,decreasing = true)] ggplot(iris) + geom_point(aes(x=sepal.width, y=sepal.length, colour=bincol(sepal.length,"blue","yellow","red")), size=4) + scale_color_identity("sepal.length", labels=labels, breaks=breaks, guide="legend")
Comments
Post a Comment