ggplot 看起来像 R 中的主效应图,但不是

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

我正在尝试生成一个看起来像主效应图的图表,但不是来自实时分析,而是输出本身。这是我的数据:

> 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

我试图生成的图表看起来像这样,每个 var 有一个方面,两个因子级别为 level1level2(对应于 1 和 2) , 线段由左侧的 level1 值和右侧的 level2 值创建。因此,最终图表应该有五个线段,斜率反映了 gain 列中的收益。

我正在尝试这个:

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

不幸的是,它产生了这个,并且在水平轴上也给出了奇数值。

我觉得我错过了一些非常直接的东西并寻求一些建议。这是数据。谢谢。

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"
))

ggplot(aes() 的前两项分别指的是 x 和 y 值,因此它有助于在数据进入 ggplot 之前将数据重塑为更长的格式。在这种情况下,我已将列名移至新列 "level" 并将其中的值移至新列 "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)