Set different limits for scale_fill_gradient in the same ggplot

时间:2018-03-25 21:07:47

标签: r ggplot2

I have code to ggplot:

df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),roi=rep(1:10,10),area=runif(100, 5.0, 7.5))
df$time <- factor(df$time, levels=rev(levels(df$time)))
  p1 <- ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
    theme_minimal()  + coord_fixed(ratio=1) +
    geom_tile(colour = "white", width = 1.0, height = 1) + 
    scale_fill_gradient(low="blue",high="red")

In the code above, the "blue" and "red" color refers to the lowest and highest values, respectively, of the column of "area". But I want to plot "area" from each "time" value with it own gradient range (it means for example "time" at 0.5, the gradient range is set by the minimum and maximum of "area" values at 0.5). Do you think it is possible to do that with ggplot. Thank you in advance!

1 个答案:

答案 0 :(得分:3)

您可以按area缩放Time条目,这样您最终会得到标准化的area Z分数,这些分数表示与每个{{1}标准差单位的零均值的差异}。

Time

enter image description here

请注意set.seed(2017); df <- data.frame( time = as.factor(rep(0.5:9.5, each = 10)), roi = rep(1:10, 10), area = runif(100, 5.0, 7.5)) library(tidyverse); df %>% mutate(time = factor(time, levels = rev(levels(time)))) %>% group_by(time) %>% mutate(area = scale(area)) %>% ggplot(aes(x=factor(roi), y=time, fill = area)) + theme_minimal() + coord_fixed(ratio=1) + geom_tile(colour = "white", width = 1.0, height = 1) + scale_fill_gradient(low="blue",high="red") 现在是Z分数;例如,值area表示此特定条目比此特定-2的平均area值低2个标准偏差。