Search code examples
rggplot2facet-wrap

ggplot that looks like main effects plot in R, but is not


I am trying to produce a chart that looks like a main effects plot, but does not come from a live analysis, just the output itself. Here is my data:

> gains.df
  var   level1   level2      gain
A  x1 12.44224 16.15509 -3.712853
B  x2 16.24322 12.35410  3.889120
C  x3 16.54085 12.05647  4.484381
D  x4 16.00008 12.59725  3.402832
E  x5 15.62463 12.97269  2.651939

The chart I am trying to produce is looking like this, with one facet per var, the two factor levels as level1 and level2 (corresponding to 1 and 2), and the line segment is created from the level1 value on the left and the level2 value on the right. Thus the final chart should have five line segments, with slopes that reflect the gains in the gain column.

enter image description here

I am trying this:

ggplot(gains.df, aes(level1,level2)) + geom_line() + facet_wrap(~var) 

Which unfortunately produces this, and gives the odd values on the horizontal axis too.

enter image description here

I feel like I am missing something very straightforward and seeking some advice. Here is the data. Thank you.

gains.df <- structure(list(var = structure(1:5, .Label = c("x1", "x2", "x3", 
"x4", "x5"), class = "factor"), level1 = c(12.4422350148863, 
16.2432212378588, 16.5408518645381, 16.0000771728686, 15.6246308859921
), level2 = c(16.155087746947, 12.3541015239745, 12.0564708972952, 
12.5972455889646, 12.9726918758412), gain = c(-3.71285273206076, 
3.88911971388437, 4.48438096724297, 3.40283158390399, 2.65193901015094
)), class = "data.frame", row.names = c("A", "B", "C", "D", "E"
))

Solution

  • The first two terms of ggplot(aes() refer to the x and y values, respectively, so it helps to reshape your data into longer format before it goes into ggplot. In this case, I've shifted the column names into a new column "level" and the values that were there into a new column "value."

    library(tidyverse)
    gains.df %>%
      select(-gain) %>%
      pivot_longer(-var, "level", "value") %>%
      # tidyr::pivot_longer is new in v1.0.0; older versions of tidyr could use:
      # tidyr::gather(level, value, -var)
      ggplot(aes(level, value, group = var)) +
      geom_line() +
      facet_wrap(~var)
    

    enter image description here