Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shrink the inner margins of legend box

Tags:

r

legend

margins

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)

enter image description here

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.

like image 831
wen Avatar asked Apr 07 '14 01:04

wen


People also ask

How do I reduce the size of a legend box in Python?

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.

How do I change the size of the legend box in R?

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.

How do I make the legend box bigger in Matplotlib?

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.


1 Answers

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

enter image description here

like image 63
koekenbakker Avatar answered Oct 28 '22 23:10

koekenbakker