22
ggplot(all, aes(x=area, y=nq)) +
  geom_point(size=0.5) +
  geom_abline(data = levelnew, aes(intercept=log10(exp(interceptmax)), slope=fslope)) + #shifted regression line
  scale_y_log10(labels = function(y) format(y, scientific = FALSE)) + 
  scale_x_log10(labels = function(x) format(x, scientific = FALSE)) + 
  facet_wrap(~levels) +
  theme_bw() +
  theme(panel.grid.major = element_line(colour = "#808080"))

And I get this figure

enter image description here

Now I want to add one geom_line to one of the facets. Basically, I wanted to have a dotted line (Say x=10,000) in only the major panel. How can I do this?

maximusdooku
  • 5,242
  • 10
  • 54
  • 94
  • maybe you could try adding another geom_abline() but with a dataset with only data for the major panel.... – MLavoie Jan 08 '16 at 21:23
  • I just have a simple equation to plot: Basically y=x+1 on the major panel – maximusdooku Jan 08 '16 at 21:25
  • One option is to create a second dataframe, such asa suggested here: http://stackoverflow.com/questions/11846295/how-to-add-different-lines-for-facets – tagoma Jan 08 '16 at 21:27
  • I think that is adding a line to all facets. – maximusdooku Jan 08 '16 at 21:33
  • 1
    Possible duplicate of [Add a segment only to one facet using ggplot2](http://stackoverflow.com/questions/24578352/add-a-segment-only-to-one-facet-using-ggplot2) – aosmith Jan 08 '16 at 23:18

2 Answers2

40

I don't have your data, so I made some up:

df <- data.frame(x=rnorm(100),y=rnorm(100),z=rep(letters[1:4],each=25))

ggplot(df,aes(x,y)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~z)

enter image description here

To add a vertical line at x = 1 we can use geom_vline() with a dataframe that has the same faceting variable (in my case z='b', but yours will be levels='major'):

ggplot(df,aes(x,y)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~z) +
  geom_vline(data = data.frame(xint=1,z="b"), aes(xintercept = xint), linetype = "dotted")

enter image description here

Rekyt
  • 354
  • 1
  • 8
Sam Dickson
  • 5,082
  • 1
  • 27
  • 45
11

Another way to express this which is possibly easier to generalize (and formatting stuff left out):

ggplot(df, aes(x,y)) +
  geom_point() + 
  facet_wrap(~ z) +
  geom_vline(data = subset(df, z == "b"), aes(xintercept = 1))

The key things being: facet first, then decorate facets by subsetting the original data frame, and put the details in a new aes if possible. Other examples of a similar idea:

ggplot(df, aes(x,y)) +
  geom_point() + 
  facet_wrap(~ z) +
  geom_vline(data = subset(df, z == "b"), aes(xintercept = 1)) + 
  geom_smooth(data = subset(df, z == "c"), aes(x, y), method = lm, se = FALSE) +
  geom_text(data = subset(df, z == "d"), aes(x = -2, y=0, label = "Foobar"))
ngm
  • 2,539
  • 8
  • 18