如何获得同样规模的多个ggplot2 scale_fill_gradientn? [英] How to get multiple ggplot2 scale_fill_gradientn with same scale?

查看:1177
本文介绍了如何获得同样规模的多个ggplot2 scale_fill_gradientn?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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)$ b(b)= bbind(d1,d2)

p1 < - ggplot(d1)
p1 < - p1 + geom_tile(aes(x = x,y = y,fill = val))
p1 < - p1 + scale_fill_gradientn(colors = 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(colors = myPalette (4))
p2

这导致下面的两个图。我的问题是,使用这种相同类型的配色方案,我该如何让两个图都使用相同的比例尺来实现价值?例如。 p1应该比p2更加统一。

p1:



p2:

解决方案使用限制 code> scale_gradientn :

  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(colors = myPalette(4),limits = c(0,4))
p2 < - p2 + scale_fill_gradientn(colors = myPalette (4),limits = c(0,4))
grid.arrange(p1,p2)



grid.arrange 东西只是为了av oid我不得不复制/粘贴两张照片。


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? E.g. p1 should be much more uniform than p2.

p1:

p2:

解决方案

Use limit in scale_gradientn:

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.

这篇关于如何获得同样规模的多个ggplot2 scale_fill_gradientn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆