Combining histograms with a density plot in R

谁都会走 提交于 2019-12-02 07:49:12

问题


It seems that I have a problem of scaling between histograms and density lines when I combine both in one plot. There is a clear visual difference between the density curve plotting alone and the combination of the two. What is the solution to have the same shape and scale between the two plots (density alone and density when combining it with histo)? I use this code:

hist(dataList[[cl12]],xlim=range(minx,maxx),breaks=seq(minx,maxx,pasx),col="grey",main=paste(paramlab,"Group",groupnum,Cl,sep=" "),xlab="",freq=FALSE) 
d<-density(dataList[[cl12]])
lines(d,col="red")

With

  dataList[[cl12]] <- c(4.399449e-02,  2.161474e-02, -1.515223e-05,  1.298059e+01,
      3.163949e-01, -1.785220e+00,  1.041053e+01,  6.327219e-01, -5.778590e-03)

Thank you for your help!


回答1:


By default hist plots bin frequencies. If you want to display the bin probabilites, so that it matches the scale of a density plot, you can use hist's freq parameter. Here's an example:

x = rnorm(1000)
plot(density(x))
hist(x, freq=F, add=T)



回答2:


Here is another way of doing the same thing.

test <- rnorm(1000)
plot(density(test))
par(new=T)
hist(test, freq=F, xaxt="n", xlab="", ylab="", main="")



回答3:


I don't think you do have a problem other than the very small number of data points. When I change your code to a reproducible version it seems fine. eg

x <- c(4.399449e-02,  2.161474e-02, -1.515223e-05,  1.298059e+01,
      3.163949e-01, -1.785220e+00,  1.041053e+01,  6.327219e-01, -5.778590e-03)

hist(x,col="grey",freq=FALSE, breaks=10) 
d<-density(x)
lines(d,col="red")

This gives an ugly plot but obviously this is because of the small number of data points:

If you do the same approach with more data points it seems fine eg:

x <- rgamma(100,1,1)

(same graphing code used)



来源:https://stackoverflow.com/questions/14986524/combining-histograms-with-a-density-plot-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!