Search code examples
rhistogramcurve

How to plot 2 curves on a histogram in base R?


I made this histogram with base R: Histogram

Here is the code:

data=read.csv("cholesterol.csv")
newdata=subset(data, data$SEX=="female")
newdata1=subset(data, data$SEX=="male")
hist(newdata$CHOLESTEROL,breaks=10,col=rgb(red = F, green = T, blue = F,
alpha = 0.3), xlim=c(0,350), ylim=c(0,25), xaxs="i", yaxs="i", las=1, main="", xlab="Cholesterol", ylab="Frequentie", border=rgb(red = F, green = T, blue = F, alpha = 0.3))
hist(newdata1$CHOLESTEROL, breaks=10,col=rgb(red = T, green = F, blue = F, alpha = 0.4), border=rgb(red = T, green = F, blue = F, alpha = 0.4), add=T)
legend('topright', c('Female','Male'),fill = rgb(0:1,1:0,0,0.4), bty='n', border = NA)

I now want to plot a curve on this histogram and I want for each group (female and male) a distinct curve. I tried several commando's (such as lines(density(newdata$CHOLESTEROL), col="red", lty=1, lwd=1)) but none of them resulted in a curve. I also could not find a solution on the internet, so I hope anyone can help me :)


Solution

  • Try adding probability=TRUE to the calls to hist. This will scale the histogram to have an area of 1, the same as the result of density so that they plot nicely together. Your code above is probably adding the curve, but with the difference in scaling it looks like a horizontal line along the bottom.