在多个数据列上使用 ggplot2 在 R 中绘制小​​提琴图

Violin Plot in R using ggplot2 on multiple data columns

我是 R 的新手,正在尝试为每个采样深度的各种物种制作物种计数数据的小提琴图。数据如下所示

    Depth Cd Cf Cl
1  3.6576  0  2  0
2  4.0000  2 13  0
3  4.2672  0  0  0
4 13.1064  0  2  0
5 14.0000  3 17 10
6 17.0000  0  0  0

第 2-5 列为物种,第 1 列为深度。我正在尝试在 R 中使用 ggplot2,但假设数据的组织方式不适合 ggplot2。理想情况下,我希望深度为 y 轴,物种为 x 轴,每个都有小提琴图。谢谢您的帮助。 亚历克斯

就像您已经怀疑的那样,您需要重塑数据。使用 tidyr::gather 将格式从 "wide" 更改为 "long",在这种情况下,这是在 x 轴上绘制物种所必需的。此外,您需要扩展可以使用 slice.

实现的计数数据


library(tidyverse)

zz <- "Depth Cd Cf Cl
1  3.6576  0  2  0
2  4.0000  2 13  0
3  4.2672  0  0  0
4 13.1064  0  2  0
5 14.0000  3 17 10
6 17.0000  0  0  0"

my_dat <- read.table(text = zz, header = T)

my_dat %>% 
  gather(species, val, -Depth) %>% 
  slice(rep(row_number(), val)) %>%
  ggplot(aes(species, Depth)) +
  geom_violin(adjust = .5)

首先重塑您的数据:

library(tidyverse)

my_dat2 <- my_dat %>% 
  gather(species, val, -Depth) %>% 
  slice(rep(row_number(), val)) %>% 
  select(-val)

ggplot(my_dat2, aes(species, Depth)) +
  geom_violin()

请注意,Cl 只有一行,因为您只有一个深度。