仅绘制数值变量的Boxplot图

时间:2014-08-22 05:40:31

标签: r

我想并排绘制一个箱形图,用于3个数值变量。数据集中没有分类变量。有没有办法做到这一点?还有变量的标签,我想在x轴上突出显示var1var2var3

数据集有0个分类变量,只有4个数值变量?

数据集是

   var1 var2      var3
1     1    3   918.280
2     3    9  8891.513
3     5   15 22479.261
4     2    4  2961.131
5     7   14 19650.198
6     1    2   377.750
7     1    5  2671.930
8     3    3   966.150
9     2    6  3765.810
10    4    8  7467.110

3 个答案:

答案 0 :(得分:1)

假设你的"数值变量"是向量,您可以创建一个包含所有三个数据框的数据框并创建箱图:

var1 <- c(1, 3, 5, 2, 7, 1, 1, 3, 2, 4)
var2 <- c(3, 9, 15, 4, 14, 2, 5, 3, 6, 8)
var3 <- c(918.28, 8891.513, 22479.261, 2961.131, 19650.198, 377.75, 2671.93, 966.15, 3765.81, 7467.11)

df <- data.frame(var1, var2, var3)
boxplot(df)

然而,规模是一个问题,因此一种替代方案可能是将三个单独的箱形图合并为一个图:

opar <- par(no.readonly = T) # Save the original graphical settings
par(mfrow = c(1,3)) # This will create a plot "matrix" with one row and three columns
boxplot(var1, main='var1')
boxplot(var2, main='var2')
boxplot(var3, main='var3')
par(opar) # Restore the original graphical settings

或根据thelatemail in his comment的建议,将y轴更改为对数比例:

boxplot(df, log='y')

答案 1 :(得分:0)

ggplot2也可以使用:

ddf = structure(list(var1 = c(1L, 3L, 5L, 2L, 7L, 1L, 1L, 3L, 2L, 4L
), var2 = c(3L, 9L, 15L, 4L, 14L, 2L, 5L, 3L, 6L, 8L), var3 = c(918.28, 
8891.513, 22479.261, 2961.131, 19650.198, 377.75, 2671.93, 966.15, 
3765.81, 7467.11), id = 1:10), .Names = c("var1", "var2", "var3", 
"id"), row.names = c(NA, -10L), class = "data.frame")

ddf
   var1 var2      var3 id
1     1    3   918.280  1
2     3    9  8891.513  2
3     5   15 22479.261  3
4     2    4  2961.131  4
5     7   14 19650.198  5
6     1    2   377.750  6
7     1    5  2671.930  7
8     3    3   966.150  8
9     2    6  3765.810  9
10    4    8  7467.110 10

ddm = melt(ddf, id='id')
library(ggplot2)
ggplot(ddm)+geom_boxplot(aes(x=variable, y=log(value)))

enter image description here

答案 2 :(得分:0)

最简单的是boxplot(var1, var2, var3)