Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plot legend: Reduce space between legend columns

Tags:

plot

r

legend

I am using vegan library to make some plots, with this code:

raremax <- min(colSums(mydata))
col <- palette()
lty <- c("solid", "dashed", "longdash", "dotdash")
pars <- expand.grid(col = col, lty = lty, stringsAsFactors = FALSE)

out <- with(pars[1:18, ], rarecurve(mydata, step = 100, sample = raremax, 
       cex =0.6, ylab="OTUs", label=F, col=col, lty=lty, lwd=2))

Then I add a legend using this code:

legend("bottomright", names(mydata), col=pars[1:18,1], lty= pars[1:18,2], 
       lwd=2, cex=0.5, xjust=1, ncol=2, x.intersp=0.5, y.intersp=0.5, bg="white")

The resulting graph looks like this: enter image description here

I would like to reduce the space between legend columns, also reducing the size of the legend box, but I can't find a way to do that.

Anyone could provide me some help?

like image 725
ALG Avatar asked Jan 08 '18 11:01

ALG


People also ask

How do I reduce the size of a legend 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.

What is Lty in legend in R?

line type (lty) can be specified using either text (“blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, “twodash”) or number (0, 1, 2, 3, 4, 5, 6). Note that lty = “solid” is identical to lty=1.

How do I remove the legend border in R?

Therefore, we can use bty="n" with the legend function and it will remove the border of the legend.


1 Answers

A combination of the legend() parameters "x.intersp" and "text.width" should be helpful.

Decreasing "x.intersp" (default value = 1, for me 0.25 looked good) should move your the legend labels closer to their respective points. Decreasing "text.width" (default value=NULL, for me 0.045 looked good) moves the columns closer together.

like image 120
Nathan Dyjack Avatar answered Oct 04 '22 15:10

Nathan Dyjack