plotting a histogram with variable bin widths using dhist?

166 views
Skip to first unread message

David L

unread,
Mar 30, 2011, 6:50:35 PM3/30/11
to ggplot2
I have found the function dhist() but I can not find any examples of
its use. I would like to use it with the following code to create
variable bin widths:

x1 <- c(rep(0, 250), rlnorm (1000))
x2 <- c(rlnorm(1250))
x <- data.frame(x1, x2)
x.long <- melt(x, measure.vars=c("x1","x2"))

ggplot(x.long, aes(x=value)) +
geom_step(aes(x=value, y=..density.., colour=variable),
stat="bin", binwidth=0.2) +
coord_cartesian(xlim = c(-1, 15))

How can I do this?

David L

unread,
Apr 1, 2011, 9:51:18 PM4/1/11
to ggplot2
Here it is, thanks to a hint from Hadley and a lot of trial and error.
I also changed the data and number of bins (nbins) so that the effect
would be more noticeable.

x1 <- c(rnorm(100,8,4), rnorm(100, 2,2), rnorm(100,0,10))
x2 <- c(rlnorm(1000),rnorm(1000,1,10), rep(1,500), rep(5,500))
ggplot() +
geom_step(aes(x1, y =..density..),
stat = 'bin',breaks = dhist(x1, nbins =20),
position = "dodge", color = 'red') +
geom_step(aes(x2, y =..density..),
stat = 'bin',breaks = dhist(x2,nbins=20),
position = "dodge", color = 'blue')

David L

unread,
Apr 2, 2011, 3:18:25 PM4/2/11
to ggplot2, myrmec...@gmail.com
Two people have told me that dhist is not available in ggplot2 version
0.8.9. I am using 0.8.8.

Hadley says that a function for calculating variable binwidths will
be available in the unreleased densityVis package: https://github.com/hadley/densityvis

I also had not read his gist on reproducible examples, which included
providing the output from sessionInfo(), which can be found below:

> sessionInfo()
R version 2.12.2 (2011-02-25)
Platform: x86_64-redhat-linux-gnu (64-bit)

locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=C LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] grid stats graphics grDevices utils datasets
methods
[8] base

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8 reshape_0.8.3 plyr_1.2.1

loaded via a namespace (and not attached):
[1] coda_0.13-5 lattice_0.19-17 rjags_2.2.0-2
Reply all
Reply to author
Forward
0 new messages