在图中标记线条

时间:2010-11-16 17:19:32

标签: r plot

我正在使用

绘制两行
plot(x, y, type = "l", color = "red")

points(x2, y2, type = "l", color = "blue")

我希望能够在每一行(而不是图例)旁边添加标签。 我很确定可以使用http://directlabels.r-forge.r-project.org/中的包。

然而,我找不到一种简单的方法。

4 个答案:

答案 0 :(得分:17)

您可以通过点击和点击方式在locator()中使用text()

y <- rnorm(100, 10)
y2 <- rnorm(100, 20)
x <- 1:100

plot(x, y, type = "n", ylim = c(0, 40), xlim = c(0, 120))
lines(x, y)
lines(x, y2, col = "red")
text(locator(), labels = c("red line", "black line)"))

alt text

答案 1 :(得分:12)

您也可以只使标签坐标成为数据的函数,而不是使用locator()。例如,捎带罗马的演示:

text(x=rep(max(x)+3, 2), y=c(mean(y), mean(y2)), pos=4, labels=c('black line', 'red line'))

答案 2 :(得分:3)

要使用直接标记,您必须在data.frame中构建数据,然后使用高级绘图系统,如ggplot2,或者在下面的示例中,格:

y <- rnorm(100, 10)
y2 <- rnorm(100, 20)
x <- 1:100
treatment <- rep(c("one group","another"),each=length(x))
df <- data.frame(x=c(x,x),y=c(y,y2),treatment)
library(lattice)
p <- xyplot(y~x,df,groups=treatment,type="l")
if(!require(directlabels)){
  install.packages("directlabels")
  library(directlabels)
}
print(direct.label(p))
print(direct.label(update(p,xlim=c(0,120)),last.points))

答案 3 :(得分:3)

locator()是一种通过点击现有图表来获取坐标的交互式方法。

以下是有关如何使用locator()为图表上的标签找到正确坐标的说明。

第1步:绘制图表:

plot(1:100)

第2步:在控制台中输入以下内容:

coords <- locator()

第3步:点击图表上的一次,然后点击图表左上角的Stop .. Stop Locator(这会将控件返回到R控制台)。

第4步:查找返回的坐标:

coords
$x
[1] 30.26407
$y
[1] 81.66773

第5步:现在,您可以使用以下坐标为现有地图添加标签:

text(x=30.26407, y=81.66773,label="This label appears where I clicked")

text(x=coords$x, y=coords$y,label="This label appears where I clicked")

结果如下:

enter image description here

您会注意到标签的中心位于您单击的位置。如果标签出现在您单击的第一个字符处,则会更好。要查找正确的参数,请参阅text的帮助,并添加参数pos=4

text(x=30,y=80,pos=4,label = "hello")

注意:

  • 标签显示在与图表上的点相同的x,y坐标中。因此, x = 100,y = 0 会出现在右下方,而 x = 0,y = 100 会出现在< strong>左上角。
  • 还可以使用legend()绘制标签(这会在标签周围绘制一个通常看起来更好的框)。
  • 有关如何更改图例中的字体以及如何将图例自动放置在图表的右上角,请参阅How to change font family in a legend in an R-plot?
  • 我建议熟悉ggplot2而不是情节,因为ggplot2是制作图表的黄金标准。