Separate binwidths for faceted histogram

1,092 views
Skip to first unread message

Tobias Heinrich

unread,
Dec 17, 2009, 12:43:17 PM12/17/09
to ggp...@googlegroups.com
Hi,

I would like to change the binwidth in a faceted histogram.

Here is an example of:
## I create some data
a <- data.frame(val=rnorm(1000, 0, 10), label="a")
b <- data.frame(val=rgamma(1000, 1, 20), label="b")
dat <- rbind(a,b)

# The v graph looks nice...
v <- ggplot(dat=dat, aes(x=val, y=..ncount..)) + geom_histogram() +
facet_grid(.~ label, scales="free")
print(v)

## ... but when I am trying to change the binwidth, the graph looks ugly.
u <- ggplot(dat=dat, aes(x=val, y=..ncount..)) +
geom_histogram(binwidth=1/50) + facet_grid(.~ label, scales="free")
print(u)

The website says that binwidth defaults to 1/30 of the range. As graph
v shows, range applies to each faceted graph, while the value of
binwidth=1/50 in graph u applies to two both histograms. (Binwidth
also doesn't take vectors; I tried that.)

The question is: How can I change the binwidth to 1/50 of the range
for each faceted graph?

Thanks so much.
Toby

PS: I am new to ggplot; so forgive me if the answer is trivial.

hadley wickham

unread,
Dec 18, 2009, 4:01:35 AM12/18/09
to Tobias Heinrich, ggp...@googlegroups.com
Hi Toby,

Currently, all panels in a layer have to have the same parameters
(mainly because I can't see any nice way of specifying varying
parameters). You should be able to work around the problem by using
separate layers:

ggplot(dat=dat, aes(x=val, y=..ncount..)) +
geom_histogram(data = subset(data, label == "a"), binwidth=1/50) +
geom_histogram(data = subset(data, label == "b"), binwidth=1/10) +


facet_grid(.~ label, scales="free")

However I'm not on a computer with R at the moment, so I can't double
check that this actually works.

Hadley

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> To post to this group, send email to ggp...@googlegroups.com
> To unsubscribe from this group, send email to
> ggplot2+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/ggplot2

--
http://had.co.nz/

sam gonzalez

unread,
Feb 8, 2018, 5:52:01 AM2/8/18
to ggplot2
I know it has been a while, but for the record your suggestion did work, Hadley. Is there a newer way these days?

Sam

Peter Szolovits

unread,
Mar 9, 2018, 6:50:54 AM3/9/18
to ggplot2
I, too, would appreciate a systematic way to do this.  I assume that for faceted plots, somewhere in the implementation of ggplot there is the equivalent of a group_by on the data to get the individual groups' data.  It would be nice if one could supply a user-defined function for the bins or binwidth parameter of geom_histogram which, when applied to the data for that facet, could compute the number of bins and/or binwidth.
--Peter Szolovits
Reply all
Reply to author
Forward
0 new messages