4

I am trying to figure how to use different coordinate systems for x and y coordinates in the text()or grid.text() functions (or any other similar functions in R).

In the example below I'd like to set the Y coordinates of the text() function at 10% from the bottom of the screen instead of using the scale of the Y scale. I can do it with grid.text() with y = 0.1 but I do not know how to set X positions of grid.text() to the X scale of the plot. Basically, I'd like to mix the capabilities of text() and grid.text() functions.

I know that grid.text has an option of passing units but I can't figure out how to use the units from the plot.

library(grid)

test= data.frame(
  x = c(1,2,3),
  y = c(12,10,3),
  n = c(75,76,73)
  )

par(mar = c(13,5,2,3))
plot(test$y ~ test$x,type="b")

text(x=test$x, y=-2, label=test$n, xpd=T)

enter image description here

Max C
  • 2,573
  • 4
  • 23
  • 28

1 Answers1

3

Rewritten:

Use grconvertY() to convert from the default 7 inch display dimensions to user coordinates:

opar <- par(mar = c(13,5,2,3))
plot(test$y ~ test$x,type="b")
text(x=test$x, y=grconvertY(0.1*7 , "in", "user") , label=test$n, xpd=T)
par(opar)

The default display is 7 inches square (at least on my machine) but you need to supply user coordinates to the text function. grconvertY and grconvertX are able to perform that conversion, although you are satisfied with the user coordinates for the X dimension so you should not use grconvertX.

enter image description here

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Thanks! I think by adding grid.text I actually confused the question. I need to use X coordinates from the plot. In your code, x is at 0.5, however I would need x to be one of the x values from the dataset, while y should at 0.1. I have no idea if this can be done. thanks – Max C May 06 '12 at 16:19
  • I think I understand what you want. You need to go from device coordinates to user coordinates to give to `text`. – IRTFM May 06 '12 at 16:25
  • Thank you! I come from SAS background where x and y coordinates can use different coordinate systems (device vs. users). I have tried to do it with grid.text by using user coordinates and device coordinates but could not get it to work. Ideally, I'd like to use different coordinate systems (devices) in TEXT function, but GRID.TEXT would be good. – Max C May 06 '12 at 16:31
  • I think I now have what you asked for. – IRTFM May 06 '12 at 16:35