ggplot2:转换图例的颜色比例,而不是比例标签

时间:2018-06-21 15:11:31

标签: r ggplot2 transform legend

我试图根据采用[0,1]中值的数字变量的值为网格中的每个矩形着色。色阶应为(黑色= 0)->(绿色= 0.05)->(红色= 1),即用于着色的变量中的“非线性”。这是我尝试过的。

library(ggplot2)
library(scales)

set.seed(1)
d <- data.frame(x = rep(1:10, each = 100), 
                y = rep(1:10, 100), 
                value = runif(1000))

scale_trans <- function(x){
  w1 <- which(!(x < 0 | x > 1) &  x <= .1)
  w2 <- which(!(x < 0 | x > 1) &  x > .1)
  out <- x
  out[w1] <- 5*out[w1]
  out[w2] <- (5/9)*out[w2] + (.5-5/90)
  return(out)
}

ascale_trans <- function(x){
  w1 <- which(!(x < 0 | x > 1) &  x <= .5)
  w2 <- which(!(x < 0 | x > 1) &  x > .5)
  out <- x
  out[w1] <- out[w1]/5
  out[w2] <- (9/5)*(out[w2] - (.5-5/90))
  return(out)
}

my_trans <- function() trans_new("my", scale_trans, ascale_trans, breaks = function(x) seq(0,1,.1), domain = c(0,1))

ggplot(d, aes(xmin=x-.5, xmax=x+.5, ymin=y-.5, ymax=y+.5)) + geom_rect(aes(fill=value)) + 
  scale_fill_gradient2(name = "Density", trans = "my", low = "black", high = "red", mid = "green", midpoint = 0.5) 

给出以下(几乎正确的)输出。

Correct colors, but ugly legend

enter image description here

但是,我希望图例上的编号是线性的并且实际颜色要转换,而不是相反。

有什么好心的人可以帮助我吗?

非常感谢

0 个答案:

没有答案