Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a frame around text fields in R base plots

Tags:

r

I have a simple scatter plot, where I want to add some text fields. Additionally, I want to put a frame around them.

Here is a toy example:

set.seed(1)
x <- rnorm(10)
y <- rnorm(10)

plot(x,y)

text(0,0,'FRAME ME PLEASE')
like image 629
Peanut Avatar asked Dec 24 '22 22:12

Peanut


2 Answers

It's possible to do this dynamically if you calculate the width and height of the string in plotting units:

set.seed(1); x <- rnorm(10); y <- rnorm(10); plot(x,y)

txt <- 'FRAME ME PLEASE'
xt <- 0
yt <- 0

text(xt, yt, txt)

sw   <- strwidth(txt)
sh   <- strheight(txt)
frsz <- 0.05

rect(
  xt - sw/2 - frsz,
  yt - sh/2 - frsz,
  xt + sw/2 + frsz,
  yt + sh/2 + frsz
)

enter image description here

It is worth noting that this can also deal with cex and font changes in the width and height calculation stages if specified.

like image 114
thelatemail Avatar answered Jan 04 '23 17:01

thelatemail


Here's another option making legend do the work.

legend(0, 0, "FRAME ME PLEASE",
    xjust = 0.5,      # 0.5 means center adjusted
    yjust = 0.5,      # 0.5 means center adjusted
    x.intersp = -0.5, # adjust character interspacing as you like to effect box width
    y.intersp = 0.1,  # adjust character interspacing to effect box height
    adj = c(0, 0.5))  # adjust string position (default values used here)
    # cex = 1.5,      # change cex if you like (not used here)
    # text.font = 2)  # bold the text if you like (not used here)

enter image description here

like image 33
Jota Avatar answered Jan 04 '23 16:01

Jota