Histogram binwidth by facet?

2,141 views
Skip to first unread message

skipperhoyer

unread,
Jan 9, 2013, 5:34:11 AM1/9/13
to ggp...@googlegroups.com
Hey there!
 
I'm trying to produce a plot showing the effect of a tranformation of my response variable. I do this by plotting histograms of the raw and transformed data. The default, range/30 gives too many bins. But setting the binwidth in the geom_histogram call sets a universal binwidth across both facets, which is not the result I want.
 
How do I set binwidth according to a factor? (In this case, the same factor that I am facetting by.)
 
Minimal working example, with some silly data:
 
##
library(ggplot2)
library(reshape)
data <- seq(from=0,to=0.2,length=100) #raw response
trans <- log(data/(1-data)) #logit transformed response
frame <- melt(data.frame(data,trans)) #collect
ggplot(data = frame, aes(x=value)) + geom_histogram() + facet_wrap(~variable, scales = "free") #default - too many bins, but they are nicel adjusted for each facet.
ggplot(data = frame, aes(x=value)) + geom_histogram(binwidth = diff(range(dat$value))/5) + facet_wrap(~variable, scales = "free") #what I want - but I want the binwidth to be 1/5 of the range *within each facet*
##
 
Thanks in advance!
Benjamin

Benjamin Høyer

unread,
Jan 9, 2013, 6:18:55 AM1/9/13
to ggp...@googlegroups.com
Hey guys
 
Sorry, my MWE didn't work - here's an improved one.
 
data <- seq(from=0.001,to=0.2,length=100)
trans <- log(data/(1-data))
frame <- melt(data.frame(data,trans))

ggplot(data = frame, aes(x=value)) + geom_histogram() + facet_wrap(~variable, scales = "free")
ggplot(data = frame, aes(x=value)) + geom_histogram(binwidth = diff(range(frame$value))/5) + facet_wrap(~variable, scales = "free")


--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

Brandon Hurr

unread,
Jan 9, 2013, 9:54:29 AM1/9/13
to Benjamin Høyer, ggplot2
Looks like you can if you precalculate things. 


#The example Takahashi-san made above didn't work because bin() is buried in ggplot2
x <- rnorm(100)
df <- ldply(c(0.1, 0.5, 1), function(bw) data.frame(bw, ggplot2:::bin(x, binwidth = bw)))
ggplot(df) + geom_histogram(aes(x, y = density, width = width), stat =
"identity") + facet_wrap(~bw)
Message has been deleted

Pierre Casadebaig

unread,
Jan 10, 2013, 4:26:15 AM1/10/13
to ggp...@googlegroups.com
Hi Benjamin,

You could find another solution in this subject : multiple calls to the same geom allow the use of different bins.

Pierre
Reply all
Reply to author
Forward
0 new messages