-1

Let's say I have a dataframe with one column x and other variables y1, y2, ... all continuos.

What's the quickest way to plot x ~ y1 and y2 on two different graphs but like they were in facet_wrap?

I know I can build multiple ggplots and use grid.arrange (but this way I am pasting the same code over and over for each y with no changes but the index of y) but is it possible to do it with facets?

Seems rather simple but I am having trouble with facets.

lucmobz
  • 453
  • 3
  • 8
  • Are you looking for something like [this](https://stackoverflow.com/questions/11014804/plotting-multiple-smooth-lines-from-a-dataframe?rq=1)? – Rui Barradas Jun 30 '19 at 11:45
  • Not really, I can plot x and y1 then I want to plot x and y2 (on a different plot) and stick these 2 plots side by side or on top of each other like in facet_wrap, which sadly only works for categorical variables. I could use grid.arrange(p1, p2, nrow = 1) where p1 and p2 are built by ggplot but I don't want to repeat the same code for p1 and p2 where they just differ by this piece of code aes(x = x, y = y1)... I wanted to know if ggplot is able to make repeated plots with the same parameters but just changing the y. – lucmobz Jun 30 '19 at 12:08

1 Answers1

1

This type of problems generaly has to do with reshaping the data. The format should be the long format and the data is in wide format.
I will use the first 3 columns of built in dataset iris as an example dataset.

library(ggplot2)

df1 <- iris[1:3]
names(df1) <- c("x", "y1", "y2")

df1_long <- reshape2::melt(df1, id.vars = "x")
head(df1_long)

ggplot(df1_long, aes(x, value, colour = variable)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  facet_grid(rows = vars(variable))

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thanks, so basically you turn variables into labels and repeat all observations. – lucmobz Jun 30 '19 at 17:29
  • @lucmobz Yes, that's it. What repeats are the id variables (there can be more than one). Note that without `facet_grid` the code would still fit two regression lines, since the `colour = variable` aesthetic is dividing the df into two. – Rui Barradas Jun 30 '19 at 18:33