1

I'm trying to make a pre-post change plot for three groups. In my data frame, pre data and post data are stored as two different variables like this.

pre_treat <- c(5,8,4,6,5,9,6,7,5)
post_treat <- c(2,2,4,10,9,11,4,5,3)
group <- c("A","A","A","B","B","B","C","C","C")
df <- data.frame(pre_treat = pre_treat,
                 post_treat = post_treat,
                 group = group)

> df
  pre_treat post_treat group
1         5          2     A
2         8          2     A
3         4          4     A
4         6         10     B
5         5          9     B
6         9         11     B
7         6          4     C
8         7          5     C
9         5          3     C

I want to plot mean values of pre_treat and post_treat for each group like the image below. I also want to plot them with group facets.

A plot I want to make

1 Answer 1

3

We could do it this way. First bring data in long format. Then calculate the mean for each group. Relevel with fct_relevel from forcats package and then plot with facet_wrap.

library(tidyverse)

df %>% 
  pivot_longer(-group) %>% 
  group_by(group, name) %>% 
  summarise(mean = mean(value)) %>% 
  mutate(name = fct_relevel(name, c("pre_treat", "post_treat"))) %>% 
  ggplot(aes(x=name, y=mean, group=1)) +
  geom_line()+
  facet_wrap(.~group)

enter image description here

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.