Reputation: 2528
I have a matrix
with 8 columns. For each row I'd like to a plot a single boxplot. I prefer the boxplots to be in a single plot. So the following example should produce 4 boxplots (8 values each) - all in a single image.
Data example:
> data[2:5,]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0.6 0.5 0.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
[2,] 0.5 0.5 0.5357143 2.5357143 0.5357143 0.5357143 0.5357143 0.5185185
[3,] 0.5 0.7 0.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
[4,] 0.5 0.5 1.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
So far I've tried:
> boxplot(data[2:5,])
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) :
'x' must be atomic
and this approach from this SO post:
> boxplot(as.list(as.data.frame(data[2:5,])))
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) :
'x' must be atomic
I've been struggling for ages. Could you please give me hint?
EDIT1:
> dput(data[2:5,])
structure(list(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.535714285714286,
0.535714285714286, 0.535714285714286, 0.535714285714286,
0.535714285714286, 0.535714285714286, 0.535714285714286,
0.535714285714286, 0.535714285714286, 0.535714285714286,
0.535714285714286, 0.535714285714286, 0.535714285714286,
0.535714285714286, 0.535714285714286, 0.535714285714286,
0.535714285714286, 0.535714285714286, 0.535714285714286,
0.535714285714286, 0.518518518518518, 0.518518518518518,
0.518518518518518, 0.518518518518518), .Dim = c(4L, 8L))
Upvotes: 1
Views: 2118
Reputation: 24178
To draw boxplots out of matrices, we can use the boxplot.matrix
function:
boxplot.matrix(data, use.cols = FALSE)
Upvotes: 6
Reputation: 263331
I think you need to use the t() function to transpose that matrix, since R generally does matrix operations on a column basis:
nums<-scan(text=" 0.6 0.5 0.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
0.5 0.5 0.5357143 2.5357143 0.5357143 0.5357143 0.5357143 0.5185185
0.5 0.7 0.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
0.5 0.5 1.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185")
Read 32 items
mat<- matrix(nums, nrow=4,byrow=TRUE)
mat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0.6 0.5 0.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
[2,] 0.5 0.5 0.5357143 2.5357143 0.5357143 0.5357143 0.5357143 0.5185185
[3,] 0.5 0.7 0.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
[4,] 0.5 0.5 1.5357143 0.5357143 0.5357143 0.5357143 0.5357143 0.5185185
> boxplot(mat) # Not correct
> boxplot( t(mat) )
After the edit we now can see that the data
-object is a rather strange one. It is a list with a dimension attribute so it gets printed as a matrix but it doesn't behave properly when passed to other functions.
Upvotes: 4