我正在尝试创建一个色彩过渡的色标.我目前正在做的是:
test <- data.frame(x = c(1:20), y = seq(0.01, 0.2, by = 0.01))
cutoff <- 0.10
ggplot(data = test,
aes(x = as.factor(x), y = y, fill = log(y), width = 1, binwidth = 0)) +
geom_bar(stat = "identity") +
scale_fill_gradientn(colours = c("red", "red", "yellow", "green"),
values = rescale(log(c(0.01, cutoff - 0.0000000000000001, cutoff, 0.2))),
breaks = c(log(cutoff)), label = c(cutoff))
Run Code Online (Sandbox Code Playgroud)
它正在制作我想要的情节.但是,颜色条中断的位置在某种程度上取决于截止值.有时低于价值,有时高于,有时在线.以下是一些具有不同截止值(0.05,0.06,0.1)的图:

我究竟做错了什么?或者,是否有更好的方法来创建这样的色标?
如果您仍然对此解决方案感兴趣,可以添加guide = guide_colourbar(nbin = <some arbitrarily large number>)到scale_fill_gradientn(). 这会增加颜色条图例使用的容器数量,从而使过渡看起来更清晰。
# illustration using nbin = 1000, & weighted colours below the cutoff
plot.cutoff <- function(cutoff){
p <- ggplot(data = test,
aes(x = as.factor(x), y = y, fill = log(y))) +
geom_col(width = 1) +
scale_fill_gradientn(colours = c("red4", "red", "yellow", "green"),
values = scales::rescale(log(c(0.01, cutoff - 0.0000000000000001,
cutoff, 0.2))),
breaks = c(log(cutoff)),
label = c(cutoff),
guide = guide_colourbar(nbin = 1000))
return(p)
}
cowplot::plot_grid(plot.cutoff(0.05),
plot.cutoff(0.06),
plot.cutoff(0.08),
plot.cutoff(0.1),
ncol = 2)
Run Code Online (Sandbox Code Playgroud)
(如果您发现上述内容在非常高的分辨率下不够清晰,您还可以设置raster = FALSE,guide_colourbar()这会关闭插值并绘制矩形。)