How can I add a line to one of the facets?

2020-02-10 18:37发布

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?

标签: r ggplot2
2条回答
Viruses.
2楼-- · 2020-02-10 18:46

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"))
查看更多
再贱就再见
3楼-- · 2020-02-10 18:50

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

查看更多
登录 后发表回答