Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add table (aligned text blocks) to plot in R

Tags:

plot

r

legend

I'd like to add a small table (for example as a legend) to a plot in R. I think of something like:

t <- wantedTableMethod(
  row("param1", "param2", "param3", "param4")
  , row(value11, value12, value13, cell(value14, adj=0))
  , row(value21, value22, value23, value24)
  , row(value31, value32, value33, cell(value34, adj=1))
  border = F
)
plot(1,1)
legend("topleft", t)

All values of a column should have the same offset. Is something like this possible in R, or do I need to align each value manually?

like image 214
R_User Avatar asked Mar 14 '13 10:03

R_User


2 Answers

If you're really averse to external packages, you can accomplish a version of this in base R as well:

plot(1, 1)
v = 1:9
legend(
  'topright', ncol = 4L, title = 'Table',
  legend = c(
    '', 'Row1', 'Row2', 'Row3',
    'Col1', v[1:3], 
    'Col2', v[4:6], 
    'Col3', v[7:9]
  )
)

Displaying the output where a simple plot has a table for a legend. The legend is titled "Table" and shows a 3x3 table with rows labeled "Row1" through "Row3" and similarly for the columns.

Caveat coder that since v will be coerced to character, you'll have to be careful about float formatting (sprintf is your friend). There are also other bells & whistles like text.col to help spiffen up the plot a bit more if you'd like.

like image 29
MichaelChirico Avatar answered Oct 15 '22 08:10

MichaelChirico


The plotrix package has a addtable2plot function you can pass a data.frame or matrix to

Using the example from the help page

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

enter image description here

It is designed to work as similarly to legend as possible.

like image 87
mnel Avatar answered Oct 15 '22 08:10

mnel