ggplot2-如何获取两个不同直方图的箱来匹配?

时间:2018-10-31 16:44:10

标签: r ggplot2 histogram

我有以下使用默认binwidth的直方图

x <- rnorm(100)
p1 <- ggplot() + geom_histogram(aes(x=x))

我希望以下直方图具有与p1完全相同的bin,

x <- rnorm(100)/2
p2 <- ggplot() + geom_histogram(aes(x=x))

换句话说,我希望p2使用与p1相同的默认垃圾箱。我该怎么做?

2 个答案:

答案 0 :(得分:2)

我们可以做的是从第一个情节中提取中断:

x1 <- rnorm(100)
p1 <- ggplot() + 
  geom_histogram(aes(x = x1))

breaks <- unique(unlist(ggplot_build(p1)$data[[1]][, c("xmin", 'xmax')]))

x2 <- rnorm(100) / 2
p2 <- ggplot() + 
  geom_histogram(aes(x = x2), breaks = breaks)

library(gridExtra)    
grid.arrange(p1, p2, nrow = 1)

enter image description here

答案 1 :(得分:0)

我认为强制相同仓位的最简单方法是对地块进行分面(因为仅设置binwidth可能会在两个不同地块的不同位置启动仓位,并使用boundary和{ {1}}将需要对可能令人讨厌的特定数据执行。另外,这使图在其轴和仓位上具有直接可比性,这大概是首先将它们放置在相同仓位上的关键点

breaks

reprex package(v0.2.0)于2018-10-31创建。