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

时间:2016-03-04 14:16:23

标签: r ggplot2 boxplot violin-plot

假设我有以下数据集1

我想在同一图表上为每个水记录器值制作箱线图。我检查过的每个地方都有一个要使用的因子变量。但是,我不想要因素,我将水记录器编号作为列名。我可以使用通用的boxplot命令执行此操作:boxplot(data$colname1, data$colname2, data$colname3, and so on)但是如何使用更好的图形来完成此操作,例如在ggplot2中。

2 个答案:

答案 0 :(得分:2)

如果没有实际数据,很难向您展示您需要使用的确切代码,但在对png进行一瞥之后,我建议您尝试以下几行:

library(reshape2)
library(ggplot2)

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

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

澄清一般过程:melt将所有列“叠加”在一起,并添加一个名为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()

的产率:

enter image description here

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

答案 1 :(得分:0)

这是基于与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