Plotting paired data for multiple groups in ggplot

Viewed 1662

Hi I want to ask how to plot paired data connected with lines in ggplot across multiple groups? Some sample data to work with:

set.seed(123)
sample <- data.frame(name = c(rep("Amy",4),rep("Bob",4),rep("Jack",4)),
                     status = rep(c("Before","After"),6),
                     test = rep(c("English","English","Math","Math"),3),
                     score = sample(60:100,12,replace=T))
sample %>% ggplot(aes(x=test,y=score,fill=status)) + 
  geom_boxplot() + geom_point(size = 2)

The idea is to have the test on the x-axis and score on the y axis as shown below but instead of having a boxplot, the individual geom_point() are stratified by status group (so points that are in the after group are in the space where the red boxplot is and points that are in the before group are in the space where the blue boxplot is) with geom_line() connecting the paired data points from the same name. Thanks!

enter image description here

1 Answers

The easiest way is to make "status" the x-aesthetic and to use facet wrap to separate the tests:

ggplot(sample, aes(x = status, y = score)) + 
geom_boxplot(aes(fill = status), alpha = .2) +
geom_line(aes(group = name)) + 
geom_point(size = 2) + 
facet_wrap(~ test)

Plot with boxplot and line

If you don't need the boxplots, you can move the "group" aesthetic to the first line.

ggplot(sample, aes(x = status, y = score, group = name)) + 
geom_line() + 
geom_point(size = 2, aes(color = status)) + 
facet_wrap(~ test, switch = "x") +
scale_x_discrete("") +
theme_minimal() +
theme(legend.position = "top", 
      panel.grid = element_blank(),
      axis.text.x = element_blank(),
      axis.line.y = element_line(size = .5))

enter image description here

Related