Different Binwidth for Each Plot of a Facet

2020-03-26 05:25发布

问题:

Trying to understand assigning unique binwidth for each factor level in geom_histogram. So far failed though.

Here is the reproducible data

a <- rnorm(10,7,0.1)
b <- rnorm(10,13,5)
df <- data.frame(data = c(a,b),group=c(rep("a",10),rep("b",10)))
kk <- df%>%
  group_by(group)%>%
  mutate(bin=density(data)$bw)

binns <- round(unique(kk$bin),digits = 2)  # to get each binwidth for each group

ggplot()+
  geom_histogram(data=kk,aes(x=data, fill=group),binwidth=binss)+
  facet_wrap(~group,scales=c("free_y"))

Error in seq.default(round_any(range[1], size, floor),    round_any(range[2],  : 
  'from' must be of length 1
Error in seq.default(round_any(range[1], size, floor), round_any(range[2],  : 
  'from' must be of length 1
Error in exists(name, envir = env, mode = mode) : 
  argument "env" is missing, with no default

Then I tried

ggplot()+
  geom_histogram(data=kk,aes(x=data, fill=group),binwidth=c(binns[1],binns[2]))+
  facet_wrap(~group,scales=c("free_y"))

The same error happened. I couldn't understand why it is giving the same error.

回答1:

You could iterate on bins to create layers

library(dplyr)
a <- rnorm(10,7,0.1)
b <- rnorm(10,13,5)
df <- data.frame(data = c(a,b),group=c(rep("a",10),rep("b",10)))
kk <- df %>%
  group_by(group) %>%
  mutate(bin=round(density(data)$bw, 2))
binns <- unique(kk$bin)

Attach ggplot2

library(ggplot2)

Create in a list one histogram layer per bin value with data only for this bin. If you have 30 level, you'll have a list of 30 histogram layers

lp_hist <- plyr::llply(binns, function(b) {
  geom_histogram(data = kk %>% 
                   filter(bin == b), 
                 aes(x = data, fill=group), 
                 binwidth = b)
  })

Combine those layers, adding them all to ggplot() object

p_hist <- Reduce("+", lp_hist, init = ggplot())

Facet and scale as you want

p_hist + facet_grid(. ~ group, scales = "free_y")

you'll obtain the graph you want that is to say a different binwidth by facet.

Watch out because 30 levels will give 30 facets... it is a lot.

Nota: Using dplyr 0.4.3, ggplot2 2.1.0 and plyr 1.8.3 on R 3.2.3



标签: r ggplot2