1

My data

ID Time Score Var1 Var 2 Var 3
1 1 100 1 2 1
1 2 150 1 2 1
2 1 200 2 3 4
2 2 -10 2 3 4
2 3 -70 2 3 4
3 1 100 1 2 2
3 2 200 1 2 2

I want to make a ggplot that combines all the variables together. Y variable is = score. X variable is = Time. and for each categorical variable (i.e., var1, var2) I want to see the effect for each level.

My code for one Graph:

var1_graph=ggplot (DB, aes(Time, Score, group_by = ID))+
facet_wrap(~var1)+
geom_smooth()+
theme_bw()
#####Var2
var2_graph = ggplot (DB, aes(Time,Score, group_by=ID))+
facet_wrap(~var2)+
geom_smooth()+
theme_bw()
################
ggarrange(var1_graph, var2_graph, labels = c("A","B"), 
ncol = 1, nrow = 2).

But this isn't what I want because I want them to be in same plot and not to combine multiple plots.

Can do this using a "Pivot_longer function"?

Thanks!

1
  • 1
    please post data using the results from dput(DB) Commented Jun 7, 2022 at 8:51

1 Answer 1

1

Are you looking for something like this?

pivot_longer is used to collect the vars in one column to enable faceting.

library(tidyverse)

tribble(
  ~ID, ~Time, ~Score, ~Var1, ~Var2, ~Var3,
  1, 1, 100, 1, 2, 1,
  1, 2, 150, 1, 2, 1,
  2, 1, 200, 2, 3, 4,
  2, 2, -10, 2, 3, 4,
  2, 3, -70, 2, 3, 4,
  3, 1, 100, 1, 2, 2,
  3, 2, 200, 1, 2, 2
) |> 
  pivot_longer(starts_with("Var"), names_to = "var", values_to = "level") |> 
  ggplot(aes(Time, Score, group = level)) +
  geom_line() +
  facet_grid(level ~ var)

Created on 2022-06-07 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

2 Comments

Each var has 4 levels. so I want the graphs to be divided into 4 graphs for each level of var. all the graph have same x axis which is time, and same y axis which is score
Do you mean like this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.