如何在同一张图上为不同的水记录器值制作多个箱线图,例如(所有列都有连续数据,没有因素)在 R

How do I make multiple boxplots on the same graph for different water logger values for example (all columns have continuous data, no factors) in R

假设我有以下数据集1

我想在同一张图上为每个水记录器值制作箱线图。我检查过的每个地方都有一个因子变量可供使用。但是,我不需要因素,我将水记录器编号作为列名。我可以使用通用的 boxplot 命令来做到这一点:boxplot(data$colname1, data$colname2, data$colname3, and so on) 但是我怎样才能用更好的图形来做到这一点,比如 ggplot2.

没有实际数据,很难向您展示您需要使用的确切代码,但在大致了解之后 png,我建议您尝试以下几行:

library(reshape2)
library(ggplot2)

df <- melt(your_data)
ggplot(df, aes(x=variable, y=value)) + geom_boxplot()

此代码可能需要一些调整。如果它不起作用并且调整不明显,请post一些示例数据,以便于我们使用它。屏幕截图中的数据意味着我们必须手动复制粘贴每个数字,很少有人愿意这样做。

阐明一般程序:melt "stacks" 所有列彼此叠加,并添加一个名为 variable 的变量,它指的是旧列名称。你可以把这个交给ggplot,说variable的不同值应该在x轴上,这就是你想要的。例如,看看 women:

head(women)
  height weight
1     58    115
2     59    117
3     60    120
4     61    123
5     62    126
6     63    129

str(women)
'data.frame':   15 obs. of  2 variables:
 $ height: num  58 59 60 61 62 63 64 65 66 67 ...
 $ weight: num  115 117 120 123 126 129 132 135 139 142 ...

您看到 women 是一个包含 15 个观测值和两列的数据框,heightweight

现在,让我们melt他们:

df <- melt(women)

head(df)
  variable value
1   height    58
2   height    59
3   height    60
4   height    61
5   height    62
6   height    63

str(df)
'data.frame':   30 obs. of  2 variables:
 $ variable: Factor w/ 2 levels "height","weight": 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  58 59 60 61 62 63 64 65 66 67 ...

现在您看到它有 30 个观察值和两列:variablevaluevariable 标识旧列。

让我们把这个交给ggplot:

ggplot(df, aes(x=variable, y=value)) + geom_boxplot()

产量:

这里有原始 women 数据集中两列的箱线图。

这是基于与 coffeinjunky 相同原则的另一个答案,但更具体到您的数据集。由于您没有提供数据集,我创建了一个具有相似列名的虚拟数据集:

d <- data.frame(x=rep(0,8))
d$`Logger 1_Water_Level` <- c(1,2,3,4,5,3,4,5)
d$`Logger 2_Water_Level` <- c(7,9,2,6,8,9,2,3)

您需要重塑数据集,以便获得标识记录器的因子变量。假设您有两个记录器并且来自记录器的数据存储在第 2 列和第 3 列中,您可以使用以下代码从存储数据的宽格式(即每个记录器的单独列)到长格式使用 ggplot2 绘图所需的格式(即用于水位测量的单列,每个记录器由名为 Logger 的列中的数字标识)

d_long <- reshape(d, varying=2:3, direction="long", timevar="Logger",v.names="Water_Level", times=1:2)
d_long$Logger <- as.factor(d_long$Logger)

现在您可以使用 ggplot2:

绘制测量值
p <- ggplot(d_long, aes(x=Logger, y=Water_Level))
p <- p + geom_boxplot()
p