如何在没有绘制符号的情况下在R中绘制图例并仍然可以很好地对齐?

时间:2014-12-17 08:42:22

标签: r plot legend

我可以创建一个没有绘图符号的图例,并且文本本身适合边框吗?

例如,在下面的代码中,我想要删除的图例文本之前有一个间隙:

plot(c(1,2,3),c(1,1,1))
abline(v=c(1.5,2,2.5),col=c("blue","red","green"))
legend("topright",legend=c("legend 1","legend 2","legend 3"),text.col=c("blue","red","green"))

1 个答案:

答案 0 :(得分:2)

你可以试试的东西:

# draw your legend without the border and with the text left-aligned and save the components :
myleg<-legend("topright",legend=c("legend 1","legend 2","leg 3"),text.col=c("blue","red","green"),plot=T,bty="n")

# get the user coordinates to adjust the gap between the text and the border
coord<-par("usr")

# add a border, closer to the text (here, gap between border and beginning of text is a hundredth of the plot width) :
rect(myleg$text$x[1]-diff(coord[1:2])/100,myleg$rect$top-myleg$rect$h,myleg$rect$left+myleg$rect$w,myleg$rect$top)

enter image description here

如果要将文本进一步向绘图中间移动,可以使用inset参数(例如:inset = 0.05): < / p>

myleg<-legend("topright",legend=c("legend 1","legend 2","leg 3"),text.col=c("blue","red","green"),plot=T,inset=0.05,bty="n")
coord<-par("usr")
rect(myleg$text$x[1]-diff(coord[1:2])/100,myleg$rect$top-myleg$rect$h,myleg$rect$left+myleg$rect$w,myleg$rect$top)

enter image description here