13

I am using geom_text to annotate plots in gglot2 and I want use relative positioning rather than absolute. That is, I want a position of (0.5, 0.5) to be dead center regardless of the x and y axis limits. Is that possible?

Alternatively I could of course transform a relative position to an absolute one if I had the x and y limits. Is it possible to extract those from a plot?

timat
  • 1,480
  • 13
  • 17
c00kiemonster
  • 22,241
  • 34
  • 95
  • 133

2 Answers2

8

If you know the range of the data in your plot, you can calculate the "true" x and y limits using the fact that ggplot using an additive expansion factor of 0.05 by default, so that the extents of the graph extend just slightly beyond the actual data values.

You can specify and multiplicative and additive expansion factor when specifying scales using expand = c(mult, add) where mult is the multiplicative factor and so on. So the default setting is expand = c(0,0.05).

joran
  • 169,992
  • 32
  • 429
  • 468
  • Yea right now I am going the long way around with the data ranges. I didn't know about specifying the expansion factor though. Thanks much. – c00kiemonster Oct 01 '11 at 02:33
  • 3
    I did not get how this works. I am facing that problem, could you extend a bit more of the explanation, maybe with a simple example? – Eduardo Jul 10 '14 at 15:10
3

Yes, it is possible to extract the x and y limits from a ggplot2-plot. This function returns the x and y coordinate of the center of a ggplot2 plot object:

center.position <- function(plot) {
xpos <- (ggplot_build(plot)$panel$ranges[[1]]$x.range[2]-ggplot_build(plot)$panel$ranges[[1]]$x.range[1])/2+ggplot_build(plot)$panel$ranges[[1]]$x.range[1]
ypos <- (ggplot_build(plot)$panel$ranges[[1]]$y.range[2]-ggplot_build(plot)$panel$ranges[[1]]$y.range[1])/2+ggplot_build(plot)$panel$ranges[[1]]$y.range[1]
return(data.frame(x=xpos,y=ypos))
}

If your x-Data is in POSIXct-format, you still have to transform it:

center.coords <- center.position(myplot)
myplot <- myplot + annotate("text",x=as.POSIXct(center.coords$x,origin="1970-01-01"), y=center.coords$y, label="X")
bfgler
  • 53
  • 8
  • 3
    The structure of `ggplot_build(plot)` has changed, by the way. In 2.1.1 it is something like `ggplot_build(plot)$layout$panel_ranges[[1]]$x.range[2]`. – Maxim.K Dec 15 '17 at 10:25