如何使用带有列表功能的标签数据框而不是 ggplot2 功能?

How use labels data frame with list function instead of ggplot2 function?

我一直在尝试寻找一种方法来绘制只有两列的数据框:一列用于值,另一列用于标签。然后,该图可以有 3 种不同的颜色(每个标签一种)。 这是我的数据框的一部分:

dN     Label
0.0293 S
0.0273 S
0.0041 S
...
0.3070 E
0.3070 E
...

所以我使用这个数据框以单独的方式创建了一个箱形图,我有 3 个数据框与上面类似。然后我使用多绘图函数进行绘图:

multiplot(dN_plot, dS_plot, omega_plot, cols=3)

这导致箱形图:

那个情节很好,但是我需要改变顺序,我需要使用其他功能。 因此,在之前的 post 中,另一位用户使用以下代码帮助我绘制了此箱线图:

list(all_dN, all_dS, all_omega) %>% 
  set_names(c("S", "M", "E")) %>% 
  map_dfr(bind_rows, .id = "df") %>% 
  pivot_longer(-df) %>%
  mutate(df = factor(df, unique(df))) %>%
  ggplot() +
  geom_boxplot(aes(x = name, y = value, color = "label"), 
               fill = "blue",
               color = "blue",
               alpha = 0.2,
               notch = T,
               notchwidth = 0.8) +
  facet_wrap(~df, nrow = 1)

我知道上面的代码有效,因为我达到了使用非常相似的数据框绘制数据的目标。 我将此代码与我的新数据框一起使用时遇到的问题是此错误:

Error: Can't combine `dN` <double> and `label` <character>.
Run `rlang::last_error()` to see where the error occurred.

我想问题出在标签或只有两列的数据框上,对吗? 我的问题是:有一种方法可以使用列表函数修复该错误,还是我需要更改 set_names? 有什么建议吗? 如果您需要重现错误,这里是数据框的一部分:

all_dN:
dN label
1   0.0293     S
2   0.0273     S
3   0.0041     M
4   0.0273     M
5   0.0041     M
6   0.0000     M
7   0.0276     S
8   0.0042     S
9   0.0000     S
10  0.0000     S
11  0.0281     E
12  0.0056     E
13  0.0015     S
14  0.0015     S
15  0.0015     S
16  0.0274     S
17  0.0071     S
18  0.0064     S
...
all_dS:
dS label
1   0.0757     S
2   0.0745     M
3   0.0085     M
4   0.0745     M
5   0.0109     M
6   0.0024     M
7   0.0741     S
8   0.0086     S
9   0.0000     S
10  0.0024     S
11  0.0798     E
12  0.0109     E
13  0.0048     E
14  0.0073     E
15  0.0049     S
16  0.0810     S
17  0.0170     S
18  0.0183     S
...
all_omega:
Omega label
1    0.3872     S
2    0.3668     M
3    0.4851     E
4    0.3668     S
5    0.3767     S
6   -1.0000     E
7    0.3730     S
8    0.4847     S
9   -1.0000     S
10  -1.0000     E
11   0.3521     E
12   0.5141     E
13   0.3078     S
14   0.2049     S
15   0.3076     S
16   0.3379     S
17   0.4189     S
18   0.3482     M

如果没有示例数据很难判断,但我认为如果替换

应该没问题
pivot_longer(-df) %>%

pivot_longer(-c(df, label)) %>%

这样 pivot_longer 只需要处理数字变量,应该很高兴 ;)

在这种情况下,您不需要使用 pivot_longer,因为您的数据已经是长格式。将所有单独的列重命名为一个名称,以便您可以将它们绑定在一起。

library(tidyverse)

list(all_dN %>% rename(value = dN), 
     all_dS %>% rename(value = dS), 
     all_omega %>% rename(value = Omega)) %>%
  set_names(c("S", "M", "E")) %>% 
  map_dfr(bind_rows, .id = "df")  %>%
  mutate(across(c(df, label), ~factor(.x, unique(.x)))) %>% 
  ggplot() +
  geom_boxplot(aes(x = label, y = value, color = "label"), 
               fill = "blue",
               color = "blue",
               alpha = 0.2,
               notch = FALSE,
               notchwidth = 0.8) +
  facet_wrap(~df, nrow = 1, scales = 'free')

我更改了 notch = FALSE 并在 facet_wrap 中添加了 scales = 'free'。您可以根据自己的喜好随意改回。