Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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?

like image 781
maximusdooku Avatar asked Jan 08 '16 21:01

maximusdooku


People also ask

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

Why is facet wrap not working in R?

This error is caused by fact that you are using $ and data frame name to refer to your variables inside the aes() . Using ggplot() you should only use variables names in aes() as data frame is named already in data= . Here is an example using diamonds dataset.


2 Answers

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"))
like image 20
ngm Avatar answered Oct 05 '22 13:10

ngm


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

like image 118
Sam Dickson Avatar answered Oct 05 '22 13:10

Sam Dickson