Comparing the density function of two specific samples in R, both areas are clearly different and cannot be equal to one (see graph linked below). I would like both areas equal one on the same graph as to determine easily the set of abscissa values for which the pdf of a sample is larger than the pdf of the other. With my script, one of the pdfs largely overlaps the other, which is almost invisible. How can I fix it? Thanks

Here are the pdfs I get when using plot() and lines():


Here are the x-values of the sample #1 (9 values):

0.043, 0.022, -0.000015,  12.98, 0.316,  -1.785, 10.410, 0.633, -0.0058

Here are the x-values of the sample #2 (448 values): Google shared text file

I use a similar script to this one (provided by ashkan):

x <- rnorm(1000, mean=3, sd=2) 
y <- rnorm(500, mean=3.5, sd=3)
dx <- density(x)
dy <- density(y)
plot.window(xlim=range(c(dx$x, dy$x)),
 ylim=range(c(dx$y, dy$y)))
with(dx, lines(x, y))
with(dy, lines(x, y, lty=2))
  • 1
    $\begingroup$ One problem is that while ashkan uses two normally distributed variables with similar means and sd, and not wildly different N, you have two bizarrely distributed variables with hugely different N. $\endgroup$
    – Peter Flom
    Feb 5, 2013 at 0:54
  • 1
    $\begingroup$ Actually, both areas are (or at least should) be unity: one area is tall and thin while the other is short and wide. Have you considered plotting the logarithms of the densities? $\endgroup$
    – whuber
    Feb 5, 2013 at 12:55
  • $\begingroup$ @whuber "plotting the logarithms of the densities?" Could you tell me more, please? How can I plot data (x, y or both?) in logarithmic scale? Isn't there any problem with negative numbers? Do you have an example of code? Thanks. $\endgroup$
    – Lio
    Feb 5, 2013 at 17:24
  • $\begingroup$ It's simple: in the plotting, every place you see y or dx$y or dy$y, replace it with its log, as in log(y), log(dx$y), or log(dy$y). $\endgroup$
    – whuber
    Feb 5, 2013 at 18:53
  • $\begingroup$ @whuber I tried but it generates the following error message: "Error in plot.window(...) : need finite 'ylim' values". There are some infinite values "-inf" (log(0)). Other idea? $\endgroup$
    – Lio
    Feb 5, 2013 at 21:28

1 Answer 1


With only 9 values, the density plot is going to be pretty sparse and I'd imagine governed a lot by your smoothing algorithm.

x1 <- c(0.043, 0.022, -0.000015,  12.98, 0.316,  -1.785, 10.410, 0.633, -0.0058)
x2 <- as.numeric(readClipboard()) #from Google
dat <- data.frame(Source=c(rep("X1",length(x1)),rep("X2",length(x2))),Value=c(x1,x2))
ggplot(dat,aes(x=Value,col=Source)) + geom_density() + scale_y_log10()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.