使用scale_fill_gradientn()将色阶转换为概率转换的颜色分布

sil*_*ita 5 r ggplot2

我正在尝试可视化重尾栅格数据,并且我想要颜色到值范围的非线性映射。有几个类似的问题,但它们并没有真正解决我的具体问题(请参阅下面的链接)。

library(ggplot2)
library(scales)

set.seed(42)
dat <- data.frame(
   x = floor(runif(10000, min=1, max=100)),
   y = floor(runif(10000, min=2, max=1000)),
   z = rlnorm(10000, 1, 1) )

# colors for the colour scale:   
col.pal <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
fill.colors <- col.pal(64)
Run Code Online (Sandbox Code Playgroud)

如果不以某种方式进行转换,数据将如下所示:

ggplot(dat, aes(x = x, y = y, fill = z)) +
   geom_tile(width=2, height=30) +
   scale_fill_gradientn(colours=fill.colors) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述我的问题是与这个这个 相关的后续问题 ,这里给出的解决方案实际上产生了我想要的图,除了图例:

qn <- rescale(quantile(dat$z, probs=seq(0, 1, length.out=length(fill.colors))))
ggplot(dat, aes(x = x, y = y, fill = z)) + 
   geom_tile(width=2, height=30) +
   scale_fill_gradientn(colours=fill.colors, values = qn)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我希望图例中的色标代表值的非线性分布(现在只有标度的红色部分可见),即图例也应该基于分位数。有办法做到这一点吗?

我认为trans色阶内的参数可能会起作用,正如这里所建议的那样 ,但这会引发错误,我认为因为qnorm(pnorm(dat$z))会产生一些无限值(虽然我不完全理解该函数..)。

norm_trans <- function(){
   trans_new('norm', function(x) pnorm(x), function(x) qnorm(x)) 
}
ggplot(dat, aes(x = x, y = y, fill = z)) + 
   geom_tile(width=2, height=30) +
   scale_fill_gradientn(colours=fill.colors, trans = 'norm')
> Error in seq.default(from = best$lmin, to = best$lmax, by = best$lstep) : 'from' must be of length 1
Run Code Online (Sandbox Code Playgroud)

那么,有人知道如何在绘图图例中进行基于分位数的颜色分布吗?

Ric*_*ord 4

此代码将通过 pnorm 转换进行手动中断。这就是你所追求的吗?

ggplot(dat, aes(x = x, y = y, fill = z)) + 
  geom_tile(width=2, height=30) +
  scale_fill_gradientn(colours=fill.colors, 
                       trans = 'norm', 
                       breaks = quantile(dat$z, probs = c(0, 0.25, 1))
  )
Run Code Online (Sandbox Code Playgroud)