我想修改颜色渐变,以匹配一组预定义的阈值/切割点和颜色。我怎么能这样做?
截止值:-0.103200,0.007022,0.094090,0.548600 颜色:"#EDF8E9","#BAE4B3","#74C476","#238B45"
#Create sample data
pp <- function (n,r=4) {
x <- seq(-r*pi, r*pi, len=n)
df <- expand.grid(x=x, y=x)
df$r <- sqrt(df$x^2 + df$y^2)
df$z <- cos(df$r^2)*exp(-df$r/6)
df
}
pp(20)->data
#create the plot
library(ggplo2)
p <- ggplot(pp(20), aes(x=x,y=y))
p + geom_tile(aes(fill=z))
#Generate custom colour ramp
library(RColorBrewer)
cols <- brewer.pal(4, "Greens")
答案 0 :(得分:4)
您可以尝试scale_fill_brewer
。首先,将您的z值加起来:
df <- pp(20)
df$z_bin <- cut(df$z, breaks = c(-Inf, -0.103200, 0.007022, 0.094090, 0.548600))
情节:
ggplot(data = df, aes(x = x, y = y, fill = z_bin)) +
geom_tile() +
scale_fill_brewer(palette = "Greens")
答案 1 :(得分:3)
使用cut
并将分档与您的颜色相匹配。我的代码假设-0.103200是向量的最小值(用于对bin的数量进行排序)。
trh <- c(-0.103200, 0.007022, 0.094090, 0.548600, Inf)
colors <- c("#EDF8E9", "#BAE4B3", "#74C476", "#238B45")
x <- runif(30, min = -0.103200, max = 1)
xc <- cut(x, breaks = trh)
colors[xc]