# Comparing and visualizing densities of two samples in R (2)

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.new()
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))

• 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. Feb 5, 2013 at 0:54
• 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?
– whuber
Feb 5, 2013 at 12:55
• @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.
– Lio
Feb 5, 2013 at 17:24
• 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).
– whuber
Feb 5, 2013 at 18:53
• @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?
– Lio
Feb 5, 2013 at 21:28

library(ggplot2)