简体   繁体   中英

multiple graphs in one plot ggplot

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 (ie, 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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM