[R] Histograms: Lines and boxes

Marc Schwartz marc_schwartz at comcast.net
Wed Jan 14 21:00:40 CET 2009


on 01/14/2009 11:53 AM Kerpel, John wrote:
> Hi folks!  I'm trying to get a histogram legend to give me a filled box
> and a line.  The problem is I keep getting both filled boxes and a line.
> How can I get rid of the second box from the code below?  
> 
>  
> 
> x<-rnorm(1000,mean=0,sd=1)
> 
>  
> 
> hist(x, breaks = 50, main="Histogram of x",freq=FALSE, 
> 
> xlab=" x", ylab="Density",col="lightblue", border="black")
> 
> x_dens<-density(x,kernel="gaussian")
> 
> points(x_dens,type="l",lwd=3)
> 
> legend("topright",legend=c("Histogram","Kernel Density
> Estimate"),lty=c(-1,1),lwd=c(-1,2),fill=c("lightblue"),merge=TRUE,inset=
> .01,cex=.8,adj=0)
> 

I am not sure that you really need to include the colored box for the
histogram in the legend, as I think that the histogram is pretty clear.

That being said, try this, using settings for points, rather than 'fill':

x <- rnorm(1000, mean = 0, sd = 1)


hist(x, breaks = 50, main = "Histogram of x", freq = FALSE,
     xlab = "x", ylab = "Density", col = "lightblue", border = "black")

x_dens <- density(x, kernel = "gaussian")

lines(x_dens, lwd = 3)

legend("topright", legend = c("Histogram", "Kernel Density Estimate"),
       lty = c(0, 1), lwd = c(0, 2),
       pch = c(22, NA),
       pt.bg = c("lightblue", NA),
       pt.cex = 1.5, pt.lwd = 1,
       inset = .01, cex = .8, adj = 0)

HTH,

Marc Schwartz




More information about the R-help mailing list