Solved – Relative density plots in R

data visualizationdensity functionr

I have a dataset with two classes, A and B, and an independent variable x. Class B is a minority class with only 1% of the observations, which tend to occur with small values of x. I am interested in the relative densities for the classes, which I would like to visualize in R.

In my imagination, I would use plot(density(data[cl=="A"]$x)/density(data$x)), but R doesn't allow division of densities. How should I do this?

Best Answer

Combining your own code with whuber's suggestions (but please bear in mind his warning), something like this might do the trick (untested):

xmin<-min(data$x)
xmax<-max(data$x)
n<-1000
Adens<-density(data[cl=="A"]$x), from=xmin, to=xmax, n=n)
Totdens<-density(data$x, from=xmin, to=xmax, n=n)

# Because each density by default has a total area of 1, rescale the y-values of Adens 
# such that its area represents the actual proportion of the A-class. Then, plot the
# ratio between both densities.
Aprop <- length(data[cl=="A"]$x)/length(data$x)
plot(Adens$x, Aprop*Adens$y/Totdens$y, type="l")

Does that work for you?