为什么箱线图没有正确显示,只是平线?

Why boxplot is not showing correctly, just flat lines?

我在 R 中使用 ggplot 或箱线图函数绘制箱线图时遇到问题。我在这里解决了一些问题,但其中 none 解决了我的问题。

我的数据集包含 20 个样本,每个样本有 10 个元素。我正在尝试制作箱形图,所以这是我到目前为止所做的:

  1. 我已经用melt函数把数据集转成long格式了(见图,只是一个元素的例子)
NC_RSD.ca.m <- melt(NC_RSD.ca, id.var="Sample")

示例数据如下:

structure(list(Sample = structure(c(15L, 16L, 17L, 18L, 19L, 
20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 
14L), .Label = c("NC10", "NC11", "NC12", "NC13", "NC14", "NC15", 
"NC16", "NC17", "NC18", "NC19", "NC20", "NC21", "NC22", "NC23", 
"NC4", "NC5", "NC6", "NC7", "NC8", "NC9"), class = "factor"), 
    Al = c(21.54055979, 13.89504614, 20.19173286, 15.39846212, 
    18.6210721, 19.3885953, 17.29371421, 13.85368756, 15.59018781, 
    14.81984326, 41.64842461, 16.29394917, 14.7150582, 21.12155266, 
    15.81993475, 11.78606019, 14.1812477, 11.70589836, 14.6093647, 
    15.21199958), Si = c(21.16836701, 10.10779796, 15.34477311, 
    18.55455665, 14.33326026, 15.76035258, 5.665395745, 5.775772135, 
    15.50099702, 8.054620606, 26.59536241, 13.85935577, 12.58568469, 
    18.7485275, 20.28945667, 6.650252061, 13.83863564, 7.741041704, 
    10.27977138, 9.224247111), S = c(205.4330401, 57.11209582, 
    93.85434886, 100.70889, 58.09909663, 40.44801629, 30.18807909, 
    45.30207695, 23.9134537, 30.28300595, 33.88869256, 45.03864953, 
    59.74444561, 39.75414202, 20.63363293, 14.07988915, 28.43671918, 
    77.72186352, 22.08674507, 35.25044782)), class = "data.frame", row.names = c(NA, 
-20L))
  1. 当我使用 ggplot 使用以下行生成箱线图时:
ggplot(data = NC_RSD_ca.m, aes(x= Sample, y=value, group = value)) + geom_boxplot(aes(fill = variable)

结果只是直线!

我的问题是如何正确显示箱线图。 我正在尝试制作与此图片类似的情节:

感谢您的帮助,在此先感谢您。

您的数据样本包含三种不同元素的测量值。如果你 reshape 为长格式,你可以得到每个 Sample 的箱线图,如下所示:

library(tidyverse)
theme_set(theme_classic())

# Reshape (melt) data to long format and set ordering of Sample
 dat.long = NC_RSD_ca.m %>% 
  gather(variable, value, -Sample) %>% 
  mutate(Sample = factor(Sample, levels=unique(Sample)))

ggplot(dat.long, aes(x= Sample, y=value)) + 
  geom_boxplot()

每个箱线图显示三个测量值的分布,一个对应于我们堆叠成长格式的每个原始元素列(AlSiS)。

如果我们添加 fill=variablecolour=variable 我们会得到扁平线,因为 Sample 和 [=20 的每个组合只有一个值(一行数据) =].单个值的箱线图将显示为一条扁平线,因为所有箱线图统计数据(中位数、四分位数和 1.5*IQR)都将等于该单个值。

ggplot(dat.long, aes(x= Sample, y=value, fill=variable, colour=variable)) + 
  geom_boxplot()

如需进一步说明,请尝试 运行 控制台中的以下示例(geom_boxplot 使用 boxplot.stats 函数计算绘图的方框和须线位置)。请注意,第二个示例中的所有 stats 都等于 1.5.

boxplot.stats(c(1,1.2,1.5,1.8,1.9,8))
boxplot.stats(1.5)  

boxplot(c(1,1.2,1.5,1.8,1.9,2))
boxplot(1.5)