Manually setting axis limits, breaks, etc. per facet

4,243 views
Skip to first unread message

Zack Weinberg

unread,
May 4, 2012, 7:45:00 PM5/4/12
to ggplot2
In 0.9, is it still impossible to manually control the arguments to
scale_x / scale_y under faceting? If not, how is it done?

Thanks,
zw

Brandon Hurr

unread,
May 8, 2012, 2:51:18 PM5/8/12
to Zack Weinberg, ggplot2
I don't know. I'm happy to try and let you know if you have a working example. 


--
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

Zack Weinberg

unread,
May 8, 2012, 5:31:15 PM5/8/12
to ggplot2
This example is a little silly, but it does illustrate the situation:

library(ggplot2)
library(reshape)

d <- melt(data.frame(A = rnorm(n=100, mean=0, sd=1),
B = rnorm(n=4000, mean=10, sd=40)),
id.vars=c())

ggplot(d, aes(x=value)) + geom_density() +
facet_wrap(~variable, scales='free_x')

# I want to set the x-axis limits to (-4,4) for facet A and (-100,
100) for facet B,
# and possibly also set manual x-axis breaks independently for each facet

Dennis Murphy

unread,
May 8, 2012, 7:20:11 PM5/8/12
to Zack Weinberg, ggplot2
Hi:

On Tue, May 8, 2012 at 2:31 PM, Zack Weinberg <za...@panix.com> wrote:
> This example is a little silly, but it does illustrate the situation:
>
> library(ggplot2)
> library(reshape)
>
> d <- melt(data.frame(A = rnorm(n=100, mean=0, sd=1),
>                     B = rnorm(n=4000, mean=10, sd=40)),
>          id.vars=c())
>
> ggplot(d, aes(x=value)) + geom_density() +
>    facet_wrap(~variable, scales='free_x')
>
> # I want to set the x-axis limits to (-4,4) for facet A and (-100,
> 100) for facet B,
> # and possibly also set manual x-axis breaks independently for each facet

In that case I think you'll have to create separate plots and then
paste them together using the gridExtra package, something like

e <- data.frame(A = rnorm(n=100, mean=0, sd=1),
B = rnorm(n=4000, mean=10, sd=40))
a <- ggplot(e, aes(x = A)) + geom_density() + xlim(-4, 4)
# The upper ylim is chosen to approximate equal y-axis
# ticks in the two plots
b <- ggplot(e, aes(x = B)) + geom_density() +
xlim(-100, 100) + ylim(0, 0.47)

library('gridExtra')
grid.arrange(a, b, nrow = 1)

AFAIK, faceting doesn't give you the level of control over individual
panels that you desire.

Dennis

Zack Weinberg

unread,
May 9, 2012, 4:30:58 PM5/9/12
to ggplot2
I'll try this with my real dataset and see how it goes. However,
while haven't used exactly this tactic in the past, I did do something
very similar (involving manual setup of grid viewports) and the plots
came out subtly misaligned, I think because the x-axis labels took up
different amounts of vertical space in each plot.

zw
Reply all
Reply to author
Forward
0 new messages