假设我有这样的图:
ggplot(iris) + geom_point(aes(x=Sepal.Width, y=Sepal.Length, colour=Sepal.Length)) + scale_colour_gradient()
离散化颜色比例的正确方法是什么,如下面的公认答案(gradient breaks in a ggplot stat_bin2d plot)所示的图?
ggplot正确地识别离散值,并对这些离散值使用离散标度,但我的问题是,如果你有连续的数据,并且你想要一个离散的颜色条(每个方块对应一个值,方块仍然在渐变中着色),那么最好的方法是什么?离散化/入库是否应该发生在ggplot之外,并作为单独的离散值列放在dataframe中,或者有没有办法在ggplot内完成?我正在寻找的一个示例类似于下面所示的规模:

只不过我画的是散点图而不是geom_tile/heatmap。
谢谢。
发布于 2013-07-18 16:34:15
这个解决方案稍微有点复杂,因为您需要一个离散的规模。否则,您可能只需使用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")

https://stackoverflow.com/questions/17713456
复制相似问题