2

I'd like to have the output of print(df.to.print) to be printed on a plot. It would be great if I could place the location with topleft or topright like in a call to `legend(...), but that's just a bonus.

Some code:

# A data.frame to play with
df.to.print <- structure(list(p.val = c(0.05, 0.1), self = c(0.0498, 0.0997), 
    H2007.REML = c(0, 0.01), H2007.ref = c(0, 0)), .Names = c("p.val", 
"self", "H2007.REML", "H2007.ref"), row.names = c(NA, -2L), class = "data.frame")

# A simple plot
plot(1)
text(1,1, df.to.print )
# All of the entries are overlapping

# I can insert newlines easily enough
plot(1)
text(1,1, paste(as.character(df.to.print), collapse='\n'))

# But that looses all of the nice formatting in the data.frame.
# Which is easy enough to get on the console with: 
print(df.to.print)

# Bonus points for 'topleft', 'topright', etc. like in legend().

Any help would be appreciated.

Nathan VanHoudnos
  • 12,923
  • 2
  • 23
  • 29
  • 1
    `addtable2plot` from **plotrix**? Or `grid.table` frmo **gridExtra** for grid graphics (ggplot/lattice). – joran Jan 14 '13 at 21:17
  • @joran That solves my problem. Could you post it as an answer along with an brief explanation of how you found those functions? I had tried some googling with no useful results. (Perhaps the answer is "experience"?) – Nathan VanHoudnos Jan 14 '13 at 21:21
  • Every user of base graphics should page through the Index page for package `plotrix`. Most of it was written by Jim Lemon, who also monitors the rhelp mailing list and provides timely responses to requests for updates and explanations. – IRTFM Jan 14 '13 at 21:25

2 Answers2

11

Try this:

plot(1)
text(0.6,1, paste(capture.output(df.to.print), collapse='\n'), pos=4, family="monospace")

pos=4 places the text to the right of the specified coordinates, and preserves left alignment. Try using a fixed-space font as well.

Theodore Lytras
  • 3,955
  • 1
  • 18
  • 25
1

Two functions that I know of that do something like this are addtable2plot from the plotrix package, which can be used with base R graphics, and grid.table from the gridExtra package which can be used with grid graphics (i.e. ggplot/lattice).

As to how I found them: I've spent a fair bit of time answering questions on SO in order to get better at R, and in the process I've discovered that "getting better at R" generally equates to "getting better at finding answers in the documentation".

The sos package is a good start.

joran
  • 169,992
  • 32
  • 429
  • 468
  • See similar question on SO as @joran suggested e.g.http://stackoverflow.com/questions/6174439/include-small-table-in-legend-in-r-graphics – java_xof Jan 14 '13 at 21:48