Last active
October 26, 2021 13:46
-
-
Save geotheory/10ae559197ad9928bbf4 to your computer and use it in GitHub Desktop.
Elegant code for quantile colour mapping in ggplot2, and a less elegant function to make pretty legend labels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require(ggplot2) | |
require(stringr) | |
d = as.vector(round(abs(10 * sapply(1:4, function(n)rnorm(20, mean=n, sd=.6))))) | |
ggplot(data=NULL, aes(x=1:length(d), y=d, col=cut(d,quantile(d)))) + | |
geom_point(size=5) + scale_colour_manual(values=rainbow(5)) | |
quantile_labels = function(d, qtls, units, round=2, minzero=F, maxplus=F, space=T){ | |
labs = levels(cut(d, qtls,include.lowest=T)) | |
for(i in c('[/(]', '[/[]', ']')) labs = stringr::str_replace_all(labs, i, '') | |
labs = stringr::str_split(labs, ',') | |
labs = lapply(labs, function(i) i = round(as.numeric(i), round)) | |
if(minzero) labs[[1]][1] = '0' | |
labs = unlist(lapply(labs, function(i) i = paste(i, collapse='-'))) | |
if(maxplus) labs[[length(labs)]] = stringr::str_replace(labs[[length(labs)]], '-[0-9]+', '+') | |
if(space) labs = paste(labs, units) else labs = paste0(labs, units) | |
labs | |
} | |
qtls = quantile(d, probs = seq(0, 1, length.out=5)) | |
quantile_labels(d, qtls, 'eggs') | |
quantile_labels(d, qtls, '%', round=0, space=F) | |
col_labs = quantile_labels(d, qtls, '%', round=0, space=F, minzero=T, maxplus=T) | |
ggplot(data=NULL, aes(x=1:length(d), y=d, col=cut(d,quantile(d)))) + geom_point(size=5) + | |
scale_colour_manual(name = "Data quantile", values=rev(rainbow(4)), labels = col_labs) + | |
guides(col = guide_legend(reverse = TRUE)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment