I am plotting a graph as follows. The code I used to generate the legend is
legend(4, 20, c("Placebo", "Progabide"), lty=1:2, pch=c(1,16), col=1:2, cex=0.8)
The problem is that the inner margin (in the vertical direction) is too big and I want to reduce it. I guess an alternate way to shrinking the inner margins is to reduce "cex" further. But then the text in the box also gets smaller. Is there a way to reduce the box but not reduce its contents.
To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method. To display the figure, use show() method.
To change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot.
To control the padding inside the legend (effectively making the legend box bigger) use the borderpad kwarg. If we change handlelength , we'll get longer lines in the legend, which looks a bit more realistic.
Here is an example how to do this with rect
, as @jbaums mentions. By using the rect information of the default legend, you can make sure the box position is correct.
plot(x=1:10,y=1:10+rnorm(10), ylim=c(0,11))
# draw default box and store size of default rect in 'a'
# disable this default rect by adding plot=F to legend()
a=legend(x=1,y=9, c("old box", "new box"), lty=1, col=2:1, cex=0.8, y.intersp=0.8,box.col=2)#,plot=F)
# box size reduced by factor 0.75
a=a$rect
mid = a$top - 0.5*a$h
reduction = 0.75
# draw new box
rect(xleft=a$left, ytop=mid+0.5*reduction*a$h, xright=a$left+a$w, ybottom=mid-0.5*reduction*a$h)
# add legend items to new box
legend(x=1,y=9, c("old box", "new box"), lty=1, col=2:1, cex=0.8, y.intersp=0.8, bty='n')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With