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?
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]
)
)
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.
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")
It is designed to work as similarly to legend
as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With