一张图上的多个箱图

时间:2013-07-24 16:55:14

标签: r boxplot

我从六个文本文件中获取数据(每个文件包含由换行符分隔的数字):

args <- commandArgs(trailingOnly = TRUE)

t0 <- read.table(paste("2_",args[1],".txt",sep=""), header=FALSE, sep="\n")
t1 <- read.table(paste("4_",args[1],".txt",sep=""), header=FALSE, sep="\n")
t2 <- read.table(paste("6_",args[1],".txt",sep=""), header=FALSE, sep="\n")
t3 <- read.table(paste("8_",args[1],".txt",sep=""), header=FALSE, sep="\n")
t4 <- read.table(paste("10_",args[1],".txt",sep=""), header=FALSE, sep="\n")
t5 <- read.table(paste("12_",args[1],".txt",sep=""), header=FALSE, sep="\n")

我想使用相同的y轴并排创建一个带有6个箱线图的图。我咨询了similar question,但没有成功。

times <- matrix(c(t0,t1,t2,t3,t4,t5), ncol=6)

png(paste(args[1],".png",sep=""))
boxplot(x = as.list(as.data.frame(times)))
dev.off()

这会产生以下错误:

Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
  'x' must be atomic
Calls: boxplot ... boxplot.stats -> <Anonymous> -> sort -> sort.default -> sort.int

我很难理解我哪里出错了。如果有人可以指导我进入写作路径或提出实现目标的另一种方式,那将非常感激。

谢谢。

修改

根据要求,下面是一个可重现的例子。

c_graph.r

#!/usr/bin/env Rscript

t0 <- read.table("t0.txt",header=FALSE, sep="\n")
t1 <- read.table("t1.txt",header=FALSE, sep="\n")
t2 <- read.table("t2.txt",header=FALSE, sep="\n")

times <- matrix(c(t0,t1,t2), ncol=3)

png("test.png")
boxplot(x = as.list(as.data.frame(times)))
dev.off()

t0.txtt1.txtt2.txt(所有内容相同):

5287
5287
58
2
525
8
758
7587
587

运行代码:

Rscript c_graph.r

结果:

Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 
  'x' must be atomic
Calls: boxplot ... boxplot.stats -> <Anonymous> -> sort -> sort.default -> sort.int

2 个答案:

答案 0 :(得分:1)

将已读入的文件转换为矩阵时会出现问题。考虑一下:

set.seed(90)

t0 <- rnorm(9)
t1 <- rnorm(9)
t2 <- rnorm(9)

times1 <- matrix(c(t0,t1,t2), ncol=6)
> times1
           [,1]       [,2]        [,3]        [,4]       [,5]       [,6]
[1,]  0.0771813  0.4425903 -0.80517064 -0.05976005 -0.5882710  0.1291539
[2,] -0.1510609  1.0055101 -0.08230689 -0.34302853 -0.1315423 -0.3980679
[3,] -0.8840764  0.9144189  0.86718542  0.87410829  1.3159242  0.0771813
[4,] -0.7205931 -0.5663887  1.65919765  0.97977040 -1.2910153 -0.1510609
[5,]  0.7407430  2.3930961 -0.24084853 -0.76047498 -0.3720799 -0.8840764


t0 <- read.table("t0.txt",header=FALSE, sep="\n")
t1 <- read.table("t1.txt",header=FALSE, sep="\n")
t2 <- read.table("t2.txt",header=FALSE, sep="\n")

times2 <- matrix(c(t0,t1,t2), ncol=3)
> times2
     [,1]      [,2]      [,3]     
[1,] Integer,9 Integer,9 Integer,9

这有效:

times3 <- data.frame(t0,t1,t2)
windows()
  boxplot(times3)

enter image description here

答案 1 :(得分:1)

将您的数据从data.frame转换为matrix似乎会遇到麻烦。您可以创建data.frames c(t0,t1,t2)列表,但只需要数值。

因此,您必须通过直接访问列来从data.frame中提取每个元素:

matrix(c(t0$V1, t1$V1, t2$V1), ncol=3)

或者您可以使用unlist

matrix(unlist(c(t0, t1, t2)), ncol=3)

或者为了避免所有这些麻烦,请将read.table替换为scan

t0 <- scan("t0.txt")