1

I would like to add a multiline text that I have constructed using splitTextGorb from the package RGraphics to a base plot. I tried the following but this doesn't work (i.e the text doesn't show on the plot)

layout(matrix(c(1,2), nrow=2, byrow=TRUE), heights = c(1,1.5))    
plot(...)
grob = splitTextGrob("This is my text")
plot.new()
vp.BottomRight <- viewport(height=unit(.5, "npc"), width=unit(0.5, "npc"), 
                       just=c("left","top"), 
                       y=0.5, x=0.5)
print(grob, vp = vp.BottonRight)

I know that mtext is an option to add text to a base plot, but I would like to use splitTextGrob specifically because it offers some flexibility that mtext or grid.text() doesn't.

Any help would be appreciated. Thank you!

Mayou
  • 8,498
  • 16
  • 59
  • 98

2 Answers2

2

This uses gridBase package to add the text to the current viewport of the plot.

library(RGraphics)
library(gridExtra)
library(gridBase)


layout(matrix(c(1,2), nrow=2, byrow=TRUE))

# First base plot
plot(1:10)

# Grid regions of base plot
vps <- baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)

# Text grob
grob <-  splitTextGrob("This is my text")
vp.BottomRight <- viewport(height=unit(.1, "npc"), width=unit(0.1, "npc"), 
                       just=c("left","top"), 
                       y=0.2, x=0.8 )
# Add text grob
pushViewport(vp.BottomRight)
grid.draw(grob)

upViewport(4) 


# Second plot
plot(1:10)
vps <- baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)
pushViewport(vp.BottomRight)
grid.draw(grob)
user20650
  • 24,654
  • 5
  • 56
  • 91
1

You'll want to use grid.draw() for grob and gTree objects.

grid.text() is only for text and plotmath expressions.

rsoren
  • 4,036
  • 3
  • 26
  • 37