Search code examples
rggplot2geom

Lines connecting group means by order of factor level (ggplot)


I am trying to create a line between the means of a numeric variable thats plotted against a factor. I want the lines to join up in the order of the factor, as demonstrated by the figure in grp_1. However, the lines join up in the order of the numeric value and not the factor, as shown in grp_2.

How can I get grp_2 to join up the same way as grp_1?

enter image description here

library(tidyverse)

# make dataset
dat <-  data.frame (level = c("level 1", "level 2", "level 3", "level 4","level 1", "level 2", "level 3", "level 4"),
                    grp = c("grp_2","grp_2","grp_2","grp_2","grp_1","grp_1","grp_1","grp_1"),
                    est = c(0, 0.739, 1.39, -1.85,0, -0.587, -1.02, -3.30)) %>% 
  as_tibble() %>% mutate(level = as.factor(level),
                         grp = as.factor(grp))
  
# make plot
dat %>% 
  ggplot(aes(x = est, y = fct_rev(level))) +
  geom_line(aes(group = grp)) +
  facet_grid(~ grp) +
  geom_vline(
    xintercept = 0,
    linetype = 6,
    size = 0.4,
    colour = "black"
  ) +
  # Add vertical line at null point
  labs(
    x = "Mean of somethong",
    y = 'Highest qualification') +
  theme_bw() 

Solution

  • You could use geom_path() instead of geom_line():

    library(tidyverse)
    # make dataset
    dat <-  data.frame (level = c("level 1", "level 2", "level 3", "level 4","level 1", "level 2", "level 3", "level 4"),
                        grp = c("grp_2","grp_2","grp_2","grp_2","grp_1","grp_1","grp_1","grp_1"),
                        est = c(0, 0.739, 1.39, -1.85,0, -0.587, -1.02, -3.30)) %>% 
      as_tibble() %>% mutate(level = as.factor(level),
                             grp = as.factor(grp))
    
    # make plot
    dat %>% 
      ggplot(aes(x = est, y = fct_rev(level))) +
      geom_path(aes(group = grp)) +
      facet_grid(~ grp) +
      geom_vline(
        xintercept = 0,
        linetype = 6,
        size = 0.4,
        colour = "black"
      ) +
      # Add vertical line at null point
      labs(
        x = "Mean of somethong",
        y = 'Highest qualification') +
      theme_bw()
    

    Created on 2022-10-19 by the reprex package (v2.0.1)