我正在使用绘制两条线
plot(x, y, type = "l", color = "red")
Run Code Online (Sandbox Code Playgroud)
和
points(x2, y2, type = "l", color = "blue")
Run Code Online (Sandbox Code Playgroud)
我希望能够在每一行旁边添加标签(而不是图例).我很确定可以在http://directlabels.r-forge.r-project.org/中使用该软件包.
然而,我找不到一种简单的方法.
Rom*_*rik 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)"))
Run Code Online (Sandbox Code Playgroud)
Mat*_*rde 12
您也可以只使标签坐标成为数据的函数,而不是使用locator().例如,在罗马的演示中捎带:
text(x=rep(max(x)+3, 2), y=c(mean(y), mean(y2)), pos=4, labels=c('black line', 'red line'))
Run Code Online (Sandbox Code Playgroud)
locator()
是一种通过单击现有图形来获取坐标的交互式方法。
以下是有关如何locator()
查找图表上标签的正确坐标的说明。
第 1 步:绘制图表:
plot(1:100)
Run Code Online (Sandbox Code Playgroud)
步骤 2:在控制台中输入以下内容:
coords <- locator()
Run Code Online (Sandbox Code Playgroud)
步骤 3:在图上单击一次,然后单击Stop .. Stop Locator
图的左上角(这会将控制权返回到 R 控制台)。
第四步:查找返回的坐标:
coords
$x
[1] 30.26407
$y
[1] 81.66773
Run Code Online (Sandbox Code Playgroud)
第 5 步:现在,您可以使用这些坐标向现有绘图添加标签:
text(x=30.26407, y=81.66773,label="This label appears where I clicked")
Run Code Online (Sandbox Code Playgroud)
或者
text(x=coords$x, y=coords$y,label="This label appears where I clicked")
Run Code Online (Sandbox Code Playgroud)
结果如下:
您会注意到标签的中心位置出现在您单击的位置。如果标签在您单击的位置显示其第一个字符,那就更好了。要找到正确的参数,请参阅 的帮助text
,并添加参数pos=4
:
text(x=30,y=80,pos=4,label = "hello")
Run Code Online (Sandbox Code Playgroud)
笔记:
legend()
绘制标签(这会在标签周围绘制一个框,通常看起来更好)。ggplot2
而不是绘图,因为这ggplot2
是生成图表的黄金标准。