Mona Jalal
Mona Jalal

Reputation: 38155

How can I show multiple plots within one panel in R?

I have the following plots and I want to show all of them within one panel! How can I do it using a matrix? Also I would like to know if there are other methods rather than using matrix and layout.

> plot(density(Boston$tax))
> rug(Boston$tax, col=2, lwd=3.5)
> hist(Boston$tax)
> rug(Boston$tax, col=2, lwd=3.5)
> table(Boston$chas)
Off  On 
471  35 
> barplot(table(Boston$chas))

> f1<-layout(matrix(c(0, 1,1,1,0,2,2,2,0,3,3,3) ,nrow = 4, ncol = 4, byrow = TRUE))
> layout.show(f1)

I want to have a structure like this for my plot 1, 2 and 3:

##      [,1] [,2] [,3] [,4]
## [1,]    0    1    1   1
## [2,]    0    2    2   2
## [3,]    0    3    3   3
## [4,]    blank0    0   0   

However the output of my code shows something different: enter image description here Can someone explain to me how is the following figure c(...) has been constructed? enter image description here

Upvotes: 2

Views: 1119

Answers (1)

Jake Burkhead
Jake Burkhead

Reputation: 6535

From ?layout

Description:

     ‘layout’ divides the device up into as many rows and columns as
     there are in matrix ‘mat’, with the column-widths and the
     row-heights specified in the respective arguments.

So if our matrix is

matrix(1:4, 2, 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4 

our lay out is like so

enter image description here

if we only want 1 plot on the top row we can specify our matrix as

matrix(c(1, 1, 2, 3), 2, 2, byrow = TRUE)
##      [,1] [,2]
## [1,]    1    1
## [2,]    2    3

and the layout will be

enter image description here

mat <- matrix(1:3, 3, 3)
mat <- rbind(cbind(0, mat), 0)
##      [,1] [,2] [,3] [,4]
## [1,]    0    1    1    1
## [2,]    0    2    2    2
## [3,]    0    3    3    3
## [4,]    0    0    0    0

enter image description here

layout(mat)

plot(density(Boston$tax))
rug(Boston$tax, col=2, lwd=3.5)
hist(Boston$tax)
rug(Boston$tax, col=2, lwd=3.5)
barplot(table(Boston$chas))

enter image description here

Upvotes: 6

Related Questions