我想在我的R-plot中添加标注文字。例如,我有一些情节:
x <- seq(0, 2, by=0.1)
y <- x*x
plot(x, y, type="l")
我想添加一些这样的标注文字:
有一些标准方法吗?
答案 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)
<强>更新强>:
您可以将text
,lines
和arrows
合并到一个小函数中:
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"))
答案 1 :(得分:2)
为了准确再现,我还会使用lines
:
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")