R中的标注文字

时间:2013-06-30 10:34:31

标签: r text graphics plot callout

我想在我的R-plot中添加标注文字。例如,我有一些情节:

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

enter image description here

我想添加一些这样的标注文字:

enter image description here

有一些标准方法吗?

2 个答案:

答案 0 :(得分:4)

查看?text(和?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

<强>更新

您可以将textlinesarrows合并到一个小函数中:

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

答案 1 :(得分:2)

为了准确再现,我还会使用lines

enter image description here

x <- seq(0, 2, by=0.1)
y <- x*x
plot(x, y, type="l")
text(0.25,2.2,'Some text')
lines(c(0, 0.5,1), c(2 ,2,1),
      lwd=3, col="grey")

arrows(0.5,2,1,1,
  lwd=3, col="grey")