When adding a geom_histogram layer to a plot that has a geom_histogram layer, the first histogram gets altered sometimes. For example, the bins change in the first layer. I added an example below. I was working on something that used the bins of the first histogram layer, and if it changes when adding subsequent layers that causes me some problems. If this is meant to happen, is there a way to prevent the first layer from changing?
suppressMessages(library(dplyr))
library(tibble)
library(ggplot2)
dtf <- c(144.8531, 192.7375, 226.3156, 200.2969,
211.3438, 215.5562, 199.6437, 190.1531,
189.6469, 216.4906) %>%
enframe()
plot1 <- dtf %>%
ggplot() +
geom_histogram(aes(value), bins = 47)
plot1
new_dtf <- c(145.2158, 189.4889, 189.4889, 193.0307,
200.1144, 200.1144, 210.7399, 216.0527,
216.0527, 226.6783) %>%
enframe()
plot2 <- plot1 +
geom_histogram(aes(value), data = new_dtf,
alpha = 0.1, fill = "red")
plot2
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
layer_data(plot1, 1) %>%
select(xmin, xmax) %>%
head()
#> xmin xmax
#> 1 144.3303 146.1012
#> 2 146.1012 147.8721
#> 3 147.8721 149.6431
#> 4 149.6431 151.4140
#> 5 151.4140 153.1849
#> 6 153.1849 154.9558
layer_data(plot2, 1) %>%
select(xmin, xmax) %>%
head()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> xmin xmax
#> 1 143.1941 144.9729
#> 2 144.9729 146.7517
#> 3 146.7517 148.5305
#> 4 148.5305 150.3093
#> 5 150.3093 152.0881
#> 6 152.0881 153.8670
Created on 2019-11-13 by the reprex package (v0.3.0)