NrSD
NrSD

Reputation: 35

How to cut a long text character in a plot in R

I have a long text that I want to plot to an image in R, the image size 300 x 200 pixel. The actual text will vary.

Example Image

enter image description here

Example Code

library(raster) 
myJPG <- stack("images/1.jpg")  # Image with 300 x 200 pixel size
plotRGB(myJPG)  

vt <- rep(1:100)
vt <- paste(vt, collapse = ' ')


text(x = 150, y = 70,
     labels = vt,
     adj = c(0.5,0.5),
     cex = 1,
     col = "white")

Example Result.

result

What I want to ask How to cut the text in labels automatically, and adjust it so all the text can be shown in the image?

Upvotes: 1

Views: 56

Answers (1)

jrcalabrese
jrcalabrese

Reputation: 2321

You can insert \n into your character vector vt to break a line. One way to do this automatically is with strwrap.

library(raster) 
myJPG <- stack("~/Documents/1.jpg")  # Image with 300 x 200 pixel size
plotRGB(myJPG)  

vt <- rep(1:100)
vt <- paste(vt, collapse = ' ')
vt2 <- paste(strwrap(
  x = vt,
  width = 70),
collapse = "\n")

text(x = 150, y = 70,
     labels = vt2,
     adj = c(0.5,0.5),
     cex = 1,
     col = "white")

enter image description here

Upvotes: 1

Related Questions