Anna Jackson
Anna Jackson

Reputation: 77

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

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

Upvotes: 2

Views: 2111

Answers (1)

Cath
Cath

Reputation: 24074

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)

enter image description here

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)

enter image description here

Upvotes: 2

Related Questions