繁体   English   中英

使用 ggplot 创建箱线图的问题

[英]Problems with creating a boxplot using ggplot

我正在尝试使用ggplot(data, aes(x, y)) + geom_boxplot创建一个箱线图,但我一开始就遇到了问题。 我的数据看起来与此类似:

    S1   S2   S3   S4   
1   4.28 4.34 4.39 4.29
2   4.13 4.11 4.62 4.91
3   4.39 4.47 4.45 4.98
4   4.09 4.98 4.18 4.01
5   4.93 4.11 4.21 4.31
6   4.26 4.15 4.62 4.04
7   4.20 4.89 4.99 4.32
8   4.19 4.16 4.76 4.89
9   4.13 4.64 4.27 4.94
10  4.20 4.87 4.47 4.05
11  4.22 4.18 4.57 4.75
12  4.23 4.08 4.27 4.41
13  4.26 4.25 4.23 4.39
14  4.23 4.01 4.26 4.17
15  4.46 4.19 4.92 4.16
16  4.27 4.15 4.50 4.85
17  4.06 4.42 4.57 4.37
18  4.14 4.36 4.47 4.47
19  4.43 4.21 4.11 4.67
20  4.29 4.15 4.56 4.26

箱线图应该在 x 轴上有五个不同的物种,在 y 轴上有值。

不幸的是,每次我将aes(x,y)定义为 species ( species <- colnames(data) ) as x :: Aesthetics must be either length 1 or the same as the data (20). x,此外,我不知道y到底要用什么以及如何编码,因为我是 R 的新手。我还使用pivot_longer包中的tidyr将数据重塑为长格式,就像另一个建议的那样题。 但是,这也不会产生箱线图。 如果我使用基本的boxplot() ,结果很好,但我需要用 ggplot 在视觉上增强箱线图。 我非常感谢所有能提供帮助的人!

你走在正确的轨道上。 如果您的数据框称为data ,您可以执行以下操作:

library(tidyverse)

data %>%
  pivot_longer(everything(), names_to = 'Species') %>%
  ggplot(aes(Species, value)) +
  geom_boxplot()

或者,如果你想变得花哨,

data %>%
  pivot_longer(everything(), names_to = 'Species') %>%
  ggplot(aes(Species, value, color = Species)) +
  geom_point(position = position_jitter(width = 0.1), alpha = 0.5) +
  geom_boxplot(fill = NA, outlier.color = NA) +
  theme_minimal(base_size = 20) +
  scale_color_brewer(palette = 'Set1')

在此处输入图像描述

创建于 2022-12-15,使用reprex v2.0.2


可重现格式的数据

data <- structure(list(S1 = c(4.28, 4.13, 4.39, 4.09, 4.93, 4.26, 4.2, 
4.19, 4.13, 4.2, 4.22, 4.23, 4.26, 4.23, 4.46, 4.27, 4.06, 4.14, 
4.43, 4.29), S2 = c(4.34, 4.11, 4.47, 4.98, 4.11, 4.15, 4.89, 
4.16, 4.64, 4.87, 4.18, 4.08, 4.25, 4.01, 4.19, 4.15, 4.42, 4.36, 
4.21, 4.15), S3 = c(4.39, 4.62, 4.45, 4.18, 4.21, 4.62, 4.99, 
4.76, 4.27, 4.47, 4.57, 4.27, 4.23, 4.26, 4.92, 4.5, 4.57, 4.47, 
4.11, 4.56), S4 = c(4.29, 4.91, 4.98, 4.01, 4.31, 4.04, 4.32, 
4.89, 4.94, 4.05, 4.75, 4.41, 4.39, 4.17, 4.16, 4.85, 4.37, 4.47, 
4.67, 4.26)), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 
"16", "17", "18", "19", "20"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM