0

I am new to R and am struggling to understand how to create a matrix line plot (or plot with line subplots) given a data set with let's say one x and 5 y-columns such that: -the first subplot is a plot of variables 1 and 2 (function of x) -the second subplot variables 1 and 3 and so on The idea is to use one of the variables (in this example number 1) as a reference and pair it with the rest so that they can be easily compared.

Thank you very much for your help.

odar
  • 391
  • 1
  • 10
  • As a place to start, here's how to make a 2x2 matrix of line plots: `par(mfrow=c(2,2)); plot(x=x, y=y1); plot(x=x, y=y2); ...` – DanY Mar 20 '19 at 19:58
  • See this https://stackoverflow.com/q/55192983/786542 – Tung Mar 20 '19 at 20:38

1 Answers1

1

Here's an example of one way to do that using tidyr and ggplot. tidyr::gather can pull the non-mpg columns into long format, each matched with its respective mpg. Then the data is mapped in ggplot so that x is mpg and y is the other value, and the name of the column it came from is mapped to facets.

library(tidyverse)
mtcars %>%
  select(rowname, mpg, cyl, disp, hp) %>%
  gather(stat, value, cyl:hp) %>%
  ggplot(aes(mpg, value)) +
  geom_point() + 
  facet_grid(stat~., scales = "free")

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53