Is there a general way to draw densities (violin plots) or histograms showing the distribution of x
along a smooth (x,y)
curve? I use this approach to show the marginal distribution of x
when there are multiple groups (e.g., different curves on one panel, delineated by differing colors).
Here is an example using the Hmisc
package's plsmo
function to get stratified loess curves and spike histograms showing the sex
-specific data density for age
.
require(Hmisc)
set.seed(1)
age <- rnorm(500, 50, 15)
y <- sample(0:1, 500, TRUE)
sex <- sample(c('female','male'), 500, TRUE)
plsmo(age, y, group=sex, col=1:2,
datadensity=TRUE, scat1d.opts=list(nhistSpike=20))
densityplot(~age, groups=sex, data=dat)
for which the ggplot2 counterpart would be:p <- ggplot( data=dat, aes( x=y, y=age, group=sex))+geom_violin(); print(p)
plsmo
is estimating the relationship between x and y usinglowess()
then computing elements of a high-resolution histogram for the distribution ofx
condition on the grouping variable and projecting the histogram onto thelowess
curve(s).plsmo
to use useggplot
.sat_smooth()
is already doing the loess part, All you left is to add the histogram just like you did inplsmo
functionggplot()
- see github.com/harrelfe/rms/blob/master/R/ggplot.Predict.s. But this function has to be provided with redundant information already known to theggplot
object, and the function takes the already-smoothed data instead of the raw data. I've also created a newgeom
--geom_plsmo
-- to use the exceptionally fastlowess()
butgeom_plsmo
does not add the histogram to the curves.