Consider the following data frame example
library('ggplot2')
library('sm')
original<-c(1:100,1)
a<-sample(original,100)
b<-rep(1:4,25)
lala<-data.frame(a,b)
My aim is to produce density plots for values in lala$a, according to each group (1,2,3,4) defined in lala$b.
For doing so in ggplot2 I could do the following
plotDensityggplot<-ggplot()+
geom_density(data = lala, aes(a, colour=factor(b)))+
theme_classic()
print(plotDensityggplot)
producing this:

However, when I plot the same data using the 'sm' package to make a formal comparison of the densities using the following code:
sm.density.compare(lala$a,as.numeric(lala$b),model = "equal")
The density curves extend beyond zero in the X-axis, despite there is no value below zero in lala$a

What's going on? - note that this affect the densities reported in the y-axis.
Is the p-value from the permutation test of equality obtained from sm.density.compare a reliable estimate? - thank you!
For what it's worth, you can (more or less) reproduce the sm output in ggplot by pre-computing densities with base R's density (I'm not familiar with sm but I imagine that sm.density calls base R's density at some point as well).
library(tidyverse)
lala %>%
group_by(b) %>%
summarise(tmp = list(map_dfc(c("x", "y"), ~density(a)[.x]))) %>%
unnest() %>%
ggplot(aes(x, y, colour = as.factor(b))) +
geom_line()

I'm not sure how geom_density (or stat_density) tune kernel density estimation parameters, but you seem to have less control over them than in base R's density.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With