aligning axes of different plots

284 views
Skip to first unread message

homer

unread,
Jun 3, 2010, 12:37:36 PM6/3/10
to ggplot2
hello ggplot2 group,
i'd really like to align the axes of a density plot and a histogram.
they have the same range but when i plot them together, the differing
number of digits in the y-axes' labels causes minor but frustrating
misalignment to the x-axis grid lines (and i'd like to have them
stacked vertically, not horizontally side-by-side).

faceting would be the standard approach, but these plots have
different layers. as far as i know, faceting does not apply to
different types of plots.

below is a simple illustration of my problem and my session info. i
know that for this example i might as well put the density layer and
the histogram layer on the same plot (via scaling the y-axes' ranges);
my actual plots have several other layers each, and putting them all
together would be overbearing.

tl;dr i'd like to align the x-axis grid lines of a histogram and a
density plot.

thanks in advance,
homer



library(ggplot2)
data(mtcars)
dens = ggplot(mtcars, aes(mpg)) + geom_density()
hist = ggplot(mtcars, aes(mpg)) + geom_histogram()
pdf("density_and_hist.pdf")
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))
vplayout = function(x, y) viewport(layout.pos.row = x, layout.pos.col
= y)
print(dens, vp = vplayout(1, 1))
print(hist, vp = vplayout(2, 1))
dev.off()

> sessionInfo()
R version 2.9.2 (2009-08-24)
x86_64-pc-linux-gnu

locale:
LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=en_US.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=C;LC_MESSAGES=en_US.UTF-8;LC_PAPER=en_US.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;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.7 digest_0.4.2 reshape_0.8.3 plyr_0.1.9
proto_0.3-8

loaded via a namespace (and not attached):
[1] tools_2.9.2

baptiste auguie

unread,
Jun 3, 2010, 2:05:41 PM6/3/10
to homer, ggplot2
Hi,

Try this

## using a hack
source("http://ggextra.googlecode.com/svn/trunk/R/align.r")

align.plots(dens, hist)


## using a dummy facetting variable
d1 <- d2 <- mtcars

d1$dummy <- "d1"
d2$dummy <- "d2"

ggplot(rbind(d1, d2), aes(mpg)) + facet_grid(dummy~., scales="free") +
geom_density(data=d1) +
geom_histogram(data=d2)

HTH,

baptiste

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

Reply all
Reply to author
Forward
0 new messages