Sam
Sam

Reputation: 4507

Adding a matrix to a plot?

Is there anyway to add a table to a plot. Suppose that I have the plot below:

curve(dnorm, -3, +4)

Now I like to add a matrix beneath the plot:

testMat <- matrix(1:20, ncol = 5)

My goal? I'm writing a plot function that not only does create a plot, but it also shows a matrix including the information I'm interested in underneath the plot.

Please see the attached picture to see what I mean. I really appreciate your help.

enter image description here

Upvotes: 7

Views: 3335

Answers (2)

Roland
Roland

Reputation: 132874

Package plotrix provides function addtable2plot.

Example from the help file:

library(plotrix)
testdf<-data.frame(Before=c(10,7,5),During=c(8,6,2),After=c(5,3,4))
rownames(testdf)<-c("Red","Green","Blue")
barp(testdf,main="Test addtable2plot",ylab="Value",
     names.arg=colnames(testdf),col=2:4)
# show most of the options
addtable2plot(2,8,testdf,bty="o",display.rownames=TRUE,hlines=TRUE,
              title="The table")

Edit: Put the table in a new plot to place it underneath your plot.

library(plotrix)

layout(matrix(c(1,2), 2, 1, byrow = TRUE),
       widths=c(1,1), heights=c(2,1))


testdf<-data.frame(Before=c(10,7,5),During=c(8,6,2),After=c(5,3,4))
rownames(testdf)<-c("Red","Green","Blue")
barp(testdf,main="Test addtable2plot",ylab="Value",
     names.arg=colnames(testdf),col=2:4)

plot.new()
addtable2plot(0,0,testdf,bty="o",display.rownames=TRUE,hlines=TRUE,
              title="The table")

Upvotes: 7

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193637

There are probably better ways to do this, but one option might be to use one of the packages that "plots" matrices and data frames, like the "gplots" package.

Here is a very bare example (you can probably customize this for much finer control over the final layout).

# Some sample data
testMat <- matrix(1:20, ncol = 5)
testMatDF <- as.data.frame(testMat)
names(testMatDF) <- c("Hey there", "Column 2", 
                      "Some * Symbols", "And ^ More", 
                      "Final Column")
rownames(testMatDF) <- paste("Group", 1:4)

# Load the package
library(gplots)
# Set par for plotting a three-row plot
par(mfrow = c(3, 1))
curve(dnorm, -3, +4)
textplot(testMat)
textplot(testMatDF)

The result:

enter image description here

You can also use layout() instead of par(mfrow...) if you want to get a little bit more creative with the placement of your plots. For example:

layout(matrix(c(1, 1, 2, 3, 3, 3), 
              2, 3, byrow = TRUE))
curve(dnorm, -3, +4)
textplot(testMat)
textplot(testMatDF)

enter image description here

Upvotes: 8

Related Questions