Add table (aligned text blocks) to plot in R

烂漫一生 提交于 2019-12-03 12:04:29

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'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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!