[英]How to get multiple ggplot2 scale_fill_gradientn with same scale?
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
And this leads to the two plots below.这导致了下面的两个图。 My question is, using this same type of color scheme, how do I get both plots to use the same scale for value?
我的问题是,使用这种相同类型的配色方案,如何让两个图使用相同的值比例? Eg p1 should be much more uniform than p2.
例如,p1 应该比 p2 更均匀。
p1: p1:
p2: p2:
Use limit
in scale_gradientn
:在
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)
The grid.arrange
stuff is just to avoid me having to copy/paste two pictures. grid.arrange
东西只是为了避免我不得不复制/粘贴两张图片。
In scale_fill_gradientn set the limits to be the same, so for example:在 scale_fill_gradientn 中将限制设置为相同,例如:
scale_fill_gradientn(colours = myPalette(4),limits=c(0,4))
And this is p1 and p2:这是 p1 和 p2:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.