[英]Label lines in a plot
我正在使用繪制兩條線
plot(x, y, type = "l", color = "red")
和
points(x2, y2, type = "l", color = "blue")
我希望能夠在每一行旁邊添加標簽(而不是圖例)。 我很確定可以在http://directlabels.r-forge.r-project.org/中使用該軟件包。
然而,我找不到一種簡單的方法。
您可以通過點擊方法在text()
使用locator()
。
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)"))
您也可以只使標簽坐標成為數據的函數,而不是使用locator()。 例如,在羅馬的演示中捎帶:
text(x=rep(max(x)+3, 2), y=c(mean(y), mean(y2)), pos=4, labels=c('black line', 'red line'))
locator()
是一種通過單擊現有圖形來獲取坐標的交互方法。
以下是有關如何使用locator()
在圖表上查找標簽的正確坐標的說明。
第1步:繪制圖表:
plot(1:100)
第2步:在控制台中鍵入以下內容:
coords <- locator()
步驟3:在繪圖上單擊一次,然后單擊Stop .. Stop Locator
在繪圖的左上角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")
結果如下:
您會注意到標簽的中心位於您單擊的位置。 如果標簽出現在您單擊的第一個字符處,則會更好。 要查找正確的參數,請參閱text
幫助,並添加參數pos=4
:
text(x=30,y=80,pos=4,label = "hello")
筆記:
legend()
繪制標簽(這會在標簽周圍繪制一個通常看起來更好的框)。 ggplot2
而不是繪圖,因為ggplot2
是生成圖形的黃金標准。 要使用直接標記,您必須在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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.