如何获取具有相同比例尺的多个ggplot2 scale_fill_gradientn?

10
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: p1

p2: enter image description here

2个回答

13

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 的作用就是避免我需要复制/粘贴两个图片。


3
看起来,grid.arrange 大约为你节省了两分钟 :P - Christie Haskell Marsh

3
在 scale_fill_gradientn 中,将限制设置为相同的值,例如:
scale_fill_gradientn(colours = myPalette(4),limits=c(0,4))

这是p1和p2:

p1

p2


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接