【问题标题】:How to get multiple ggplot2 scale_fill_gradientn with same scale?如何获得具有相同比例的多个 ggplot2 scale_fill_gradientn?
【发布时间】:2014-03-06 20:46:19
【问题描述】:
library(ggplot2)
library(cumplyr)
library(scales)
library(RColorBrewer)


myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))

x   = 1:5
y   = 1:5
pts = cartesian_product(c('x','y'))
d1 = cbind(pts, runif(nrow(pts),min=0,max=1), 1)
d2 = cbind(pts, runif(nrow(pts),min=0,max=4), 2)
colnames(d1) = colnames(d2) = c("x","y","val","k")
d  = rbind(d1,d2)

p1 <- ggplot(d1)
p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))
p1 <- p1 + scale_fill_gradientn(colours = myPalette(4))
p1

p2 <- ggplot(d2, aes(x = x, y = y, fill = val))
p2 <- p2 + geom_tile(aes(x = x, y = y, fill = val)) 
p2 <- p2 + scale_fill_gradientn(colours = myPalette(4))
p2

这导致了下面的两个图。我的问题是,使用这种相同类型的配色方案,我如何让两个图使用相同的值比例?例如。 p1 应该比 p2 更均匀。

p1:

p2:

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    scale_gradientn 中使用limit

    p1 <- ggplot(as.data.frame(d1))
    p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))
    
    p2 <- ggplot(as.data.frame(d2), aes(x = x, y = y, fill = val))
    p2 <- p2 + geom_tile(aes(x = x, y = y, fill = val)) 
    library(gridExtra)
    
    p1 <- p1 + scale_fill_gradientn(colours = myPalette(4), limits=c(0,4))
    p2 <- p2 + scale_fill_gradientn(colours = myPalette(4), limits=c(0,4))
    grid.arrange(p1, p2)
    

    grid.arrange 只是为了避免我不得不复制/粘贴两张图片。

    【讨论】:

    • 从外观上看,grid.arrange 为您节省了大约两分钟:P
    【解决方案2】:

    在 scale_fill_gradientn 中将限制设置为相同,例如:

    scale_fill_gradientn(colours = myPalette(4),limits=c(0,4))
    

    这是 p1 和 p2:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 2020-06-24
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多