How to add an abline to just one plot in facet wrap?

4,782 views
Skip to first unread message

Luke

unread,
Sep 10, 2010, 6:44:04 PM9/10/10
to ggplot2
Hi all,

I am looking for a way to add an abline to just one plot in facet
wrap. I was hoping I could find something simple like

FC + geom_abline(slope = 1.08, intercept = 0, size = 1, ......)

where the ..... would define the plot within FC where I wanted to draw
the line, but my search has turned up nothing thus far. I have just
started using facet wrap and any help would be appreciated. A generic
version of my code is below

FC <- ggplot(facet.ex, aes(X, Y)) + geom_abline(slope = 1, intercept =
0, colour = "white", size = 1) + geom_smooth(method = "lm", se = F) +
facet_wrap(~variable)
FC <- FC + layer(geom = "point", size = 2) + coord_cartesian(xlim =
c(-5,105), ylim = c(-5,105))+ scale_x_continuous(breaks =
c(0,20,40,60,80,100)) + scale_y_continuous(breaks =
c(0,20,40,60,80,100)) + labs(x = "Label X", y = "Label Y")
FC


Edit: I found someone with a similar problem who just subset the data
by using +geom_abline(data=subset(facet.ex, variable == "a"), slope =
1.08, intercept = 0). This works but is there a way to define the
specific plot using coordinates of the grid instead?

Allan

unread,
Sep 10, 2010, 11:54:21 PM9/10/10
to ggplot2
I think you found Hadley's response which was to use the subset
command and not to think about picking a facet:
http://stackoverflow.com/questions/1570379/adding-stat-smooth-in-to-only-1-facet-in-ggplot2
That leaves you more flexible if you later adjust the layout of your
grid. I don't know of a way to target specific locations in the grid
apart from using the faceting variables.

# reproducible example
library(ggplot2)
data(mpg)
p <- ggplot(mpg, aes(hwy, cty)) + geom_point()
p + geom_abline(intercept = 20, slope = 0, subset = .(cyl == 4)) +
facet_wrap(~cyl)

# I don't quite entirely understand the following behavior
# if you try using subset with geom_hline instead of geom_abline you
need to map the yintercept in an aes call

# doesn't work
p + geom_hline(yintercept = 20, subset = .(cyl == 4)) +
facet_wrap(~cyl)
## Error in eval(expr, envir, enclos) : object 'cyl' not found
# alternative subset syntax just gets ignored
p + geom_hline(yintercept = 20, data = subset(mpg, cyl == 4)) +
facet_wrap(~cyl)

# both work after you map
p + geom_hline(aes(yintercept = 20), subset = .(cyl == 4)) +
facet_wrap(~cyl)
p + geom_hline(aes(yintercept = 20), data = subset(mpg, cyl == 4)) +
facet_wrap(~cyl)


Thanks,
Allan
(R 2.11.1; x86_64-pc-linux-gnu; ggplot2_0.8.8 proto_0.3-8
reshape_0.8.3 plyr_1.1)
Reply all
Reply to author
Forward
0 new messages