Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend box width not correct when using par

Tags:

plot

r

width

legend

I have the problem , that my legend is too large, my code:

par(mfrow=c(1,2))
hist(alvsloss,breaks = 100, freq=F,main="Histogramm,
 density curve (gaussian kernel) \n and fitted normal distribution of Allianz simple losses ",xlim=c(-0.15,0.15),xlab="loss",ylab="density",cex.axis=1.2,cex.lab=1.2)
lines(density(alvsloss), col="black", lwd=2)
curve(dnorm(x, mean = mean(alvsloss), sd = sd(alvsloss)), add=TRUE, col="black",lwd=2,lty="dotted")

legend(-0.155, 30, c("(Gaussian) Kernel density","fitted normal distribution"),lwd=2, cex=0.8, 
   col=c("black","black"), lty=1:2)


qqnorm(alvsloss,main="normal QQ Plot",cex.axis=1.2,cex.lab=1.2)
qqline(alvsloss)

This gives the following picture:

Graphs

The problem is, that the legend on the left is too big, how can I control the width of the box? The box is way too large.

data can be found here: http://uploadeasy.net/upload/ocafq.rar

like image 575
Stat Tistician Avatar asked Mar 15 '13 15:03

Stat Tistician


People also ask

How do I resize a 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 you put a legend in the top right corner in R?

To set the legend on top-right side we can use legend. position="top" and legend. justification="right".

How do you set the position of a legend in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.


1 Answers

The white space on the right of you legend tells me that you manually widened your plot window. Legends do not scale well when it comes to manual re-sizing.

The solution is opening a plot of the exact size you need before plotting. In Windows, this is done with windows(width=10, height=8). Units are in inches. The surrounding box should now be tighter with the text.

If this is still not satisfactory, you should try:

  1. Reducing the font size of the legend cex=0.7
  2. Removing the box around the legend bty = "n" and using \n to split your legend onto several lines
  3. You can put your legend even more on the left using "topleft" instead of coordinates

Here's how I would do it:

legend("topleft", 
 legend=c("(Gaussian)\nKernel\ndensity","Fitted\nnormal\ndistribution\n"),
 bty = "n",lwd=2, cex=0.7, col=c("black","black"), lty=1:2)

enter image description here

like image 60
Pierre Lapointe Avatar answered Sep 30 '22 14:09

Pierre Lapointe