Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Box and line in R plot Legend

Tags:

plot

r

I've done a plot, and have one small problem which drive me crazy with the legend part

I can't find a way to center the box in the legend.

x=seq(-4,4,length=200)
 y=dnorm(x,mean=0.816783035,sd=0.862916258)
 plot(x,y,type="l",lwd=2,col="red" , xlim=c(-4, 4) ,  ylab="probabilitiy", xlab="")


 #Shaded Area TBR!
 c= -0.211653725


 x=seq(-4,4,length=200)
 y=dnorm(x,mean=-0.393475584,sd=0.895660247)
 lines(x,y,type="l",lwd=2,col="blue")


 legend("topright", legend = c('TBR', 'TBF', 'Criterion', 'Hit'), 
               bty = "n",
               col = c("green", "blue", "red",NA),
               lty = c(1,1,1,NA),
               density=c(0,0,0,10),
               fill = c("green", "blue", "red","red"),
               border = c(NA,NA,NA,"red"),
               )
 abline(v= c)

 x1 = seq(c,4, length = 200)
 y1 = dnorm(x1,mean=0.816783035,sd=0.862916258)

polygon(c(c,x1) ,c(0, y1),density= 3, col="red")

enter image description here

like image 414
Boo Avatar asked May 20 '14 23:05

Boo


People also ask

What is Cex in legend in R?

cex. character expansion factor relative to current par("cex") . Used for text, and provides the default for pt. cex . pt.cex.

What is inset in legend in R?

inset. inset distance(s) from the margins as a fraction of the plot region when legend is placed by keyword. xpd. if supplied, a value of the graphical parameter xpd to be used while the legend is being drawn. title.col.

How do I make my legend box smaller 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.


1 Answers

It's the "x.intersp" parameter you will need to play with I think. Try:

x=seq(-4,4,length=200)
 y=dnorm(x,mean=0.816783035,sd=0.862916258)
 plot(x,y,type="l",lwd=2,col="red" , xlim=c(-4, 4) ,  ylab="probabilitiy", xlab="")


 #Shaded Area TBR!
 c= -0.211653725


 x=seq(-4,4,length=200)
 y=dnorm(x,mean=-0.393475584,sd=0.895660247)
 lines(x,y,type="l",lwd=2,col="blue")


 legend("topright", legend = c('TBR', 'TBF', 'Criterion', 'Hit'), 
               bty = "n",
               col = c("green", "blue", "red",NA),
               lty = c(1,1,1,NA),
               density=c(0,0,0,10),
               fill = c("green", "blue", "red","red"),
               border = c(NA,NA,NA,"red"), 
               x.intersp=c(2,2,2,0.5)
               )
 abline(v= c)

 x1 = seq(c,4, length = 200)
 y1 = dnorm(x1,mean=0.816783035,sd=0.862916258)

polygon(c(c,x1) ,c(0, y1),density= 3, col="red")

enter image description here

Does that do what you want?

like image 151
ThatGuy Avatar answered Oct 30 '22 01:10

ThatGuy