How can I plot a legend in R without plotting symbols and still get it to align nicely?

余生颓废 提交于 2019-12-24 05:34:45

问题


Can I create a plot legend which doesn't have plotting symbols and that the text itself is fitted to the border box?

For example, in the following code there is a gap before the legend text that I want to get rid of:

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:


Something you can try :

# 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)

If you want to move the text further towards the middle of the plot, you can use inset parameter (eg: inset=0.05) :

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)



来源:https://stackoverflow.com/questions/27521394/how-can-i-plot-a-legend-in-r-without-plotting-symbols-and-still-get-it-to-align

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!