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.
You could iterate on bins to create layers
Attach
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
Combine those layers, adding them all to
ggplot()
objectFacet and scale as you want
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
andplyr 1.8.3
onR 3.2.3