Search code examples
rtextgraphicsplotcallout

Callout text in R


I want add callout text to my R-plot. For example, I have some plot:

x <- seq(0, 2, by=0.1)
y <- x*x
plot(x, y, type="l")

enter image description here

I want to add some callout text like this:

enter image description here

There are some standard methods for it?


Solution

  • Have a look at ?text (and ?arrows).

    x <- seq(0, 2, by=0.1)
    y <- x*x
    plot(x, y, type="l")
    
    text(0.25, 2, "Some text", pos=3)
    arrows(0.25, 2, 1, 1)
    

    calloutplot1

    UPDATE:

    You could combine text, lines and arrows into a small function:

    x <- seq(0, 2, by=0.1)
    y <- x*x
    plot(x, y, type="l")
    
    # x0, y0: coordinates of text; see ?text
    # x1, y1: coordinates to which the arrows are drawn; see ?arrows
    # labels: text
    # vOffset/hOffset: vertical/horizontal offset
    callout <- function(x0, y0, x1, y1, labels, vOffset=0.25, hOffset=0.25) {
      ## fetch labels width/height
      w <- strwidth(labels)
      w2 <- w/2
      h <- strheight(labels)
      h2 <- h/2
    
      ## draw text
      text(x0, y0, labels=labels)
    
      ## calulate arrow starting point/line end point
      x01 <- x0+w2*(1+hOffset)
      y01 <- y0-h2*(1+vOffset)
    
      ## draw horizontal lines
      for (i in seq(along=x0)) {
        lines(c(x0[i]-w2[i], x01[i]), c(y01[i], y01[i]))
      }
    
      ## draw arrows
      arrows(x0=x01, y0=y01, x1=x1, y1=y1)
    }
    
    callout(c(0.25, 0.25), c(2, 3), c(1, 1.5), c(1, 2.25),
            c("Some text", "Some other text"))
    

    calloutplot2