Reputation: 111
I have to compare the density function of two samples in R. Surprisingly, whatever the function I use, plot(), lines() or ggplot, one of both samples either does not appear or both areas are different and cannot be equal to one. 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. How can I solve it? Many thanks for your help.
1/ Using ggplot, the script is:
require ("ggplot2")
p2<-density(tabgroupcl2$B, n=1000)
p1<-density(tabgroupcl1$B, n=1000)
dat <- data.frame(dens = c(p1$x, p2$x)
, lines = rep(c("cl1", "cl2")), each=1000)
ggplot(dat,aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)
2/ Where Density(tabgroupcl2$B):
Call:
density.default(x = tabgroupcl2$B)
Data: tabgroupcl2$B (348 obs.); Bandwidth 'bw' = 0.001689
x y
Min. :-91.95 Min. : 0.0000
1st Qu.:-34.07 1st Qu.: 0.0000
Median : 23.80 Median : 0.0000
Mean : 23.80 Mean : 0.4613
3rd Qu.: 81.68 3rd Qu.: 0.0000
Max. :139.56 Max. :179.2431
3/ Where Density(tabgroupcl1$B):
Call:
density.default(x = tabgroupcl1$B)
Data: tabgroupcl1$B (9 obs.); Bandwidth 'bw' = 0.2738
x y
Min. :-2.607 Min. :0.0000000
1st Qu.: 1.495 1st Qu.:0.0000000
Median : 5.598 Median :0.0001349
Mean : 5.598 Mean :0.0608673
3rd Qu.: 9.700 3rd Qu.:0.0548682
Max. :13.802 Max. :0.7583033
Upvotes: 0
Views: 1574
Reputation: 679
This is how I overlayed two datasets columns in one plot:
Here I am creating a new column (samediff) in each dataframe with repeating text in the column to identify it.
same_auditor$samediff <- "same"
diff_auditor$samediff <- "diff"
Combining the datasets for the plot.
samescore <- same_auditor$Audit_Score
diffscore <- diff_auditor$Audit_Score
sameDiffcombined <- rbind(diff_auditor,same_auditor)
ggplot(sameDiffcombined, aes(Audit_Score, fill = samediff)) + geom_density(alpha = 0.5)
Upvotes: 0
Reputation: 4930
Peter Ellis' answer is exactly right. Here's a "ground up" example of how you might estimate and plot densities from two different samples on the same axis:
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))
axis(1)
axis(2)
legend(topright, lty=1:2, c('x', 'y'))
mtext(side=1, line=2, 'Observed values')
mtext(side=2, line=2, 'Estimated probability mass')
title('Smoothed Density Estimates for 2-sample experiment')
Upvotes: 1
Reputation: 5904
It looks like you are using the x values from a density object in your ggplot() function as though they were the original data. I don't see why you would want to do this, but if so you also need to use the y values - and you don't need the density stat in ggplot at all. Alternatively, let the density stat do the work and use your original data.
Upvotes: 1