-2

I'm trying to do a plot with facets with some data from a previous model. As a simple example:

t=1:10;
x1=t^2;
x2=sqrt(t);
y1=sin(t);
y2=cos(t);

How can I plot this data in a 2x2 grid, being the rows one factor (levels x and y, plotted with different colors) and the columns another factor (levels 1 and 2, plotted with different linetypes)?

Note: t is the common variable for the X axis of all subplots.

  • you can use `dput(head(dataset))`, to create a small sample of your dataset. If you wish you can add it here as well. – Sal-laS Sep 09 '18 at 16:50
  • Possible duplicate of [Generating Multiple Plots in ggplot by Factor](https://stackoverflow.com/questions/31798162/generating-multiple-plots-in-ggplot-by-factor) – divibisan Sep 10 '18 at 17:43

1 Answers1

1

ggplot will be more helpful if the data can be first put into tidy form. df is your data, df_tidy is that data in tidy form, where the series is identified in one column that can be mapped in ggplot -- in this case to the facet.

library(tidyverse)
df <- tibble(
  t=1:10,
  x1=t^2,
  x2=sqrt(t),
  y1=sin(t),
  y2=cos(t),
)

df_tidy <- df %>%
  gather(series, value, -t)

ggplot(df_tidy, aes(t, value)) + 
  geom_line() +
  facet_wrap(~series, scales = "free_y")

enter image description here

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