Hantabaru
Hantabaru

Reputation: 121

How to create a density plot of all data overlaid with a density plot of a subset of the data in ggplot

I have a data set that appears to have a binomial distribution.

The data is a health related quality of life survey and can be subsetted according to types of training activity

I am wondering if I can overlay a density plot of the data as a whole with density plots of the training activity subsets

The data set is called hrql.scores and subset of the data with a particular training background is apdj and a second subset is health.studio. The test data I want to plot is the column with the heading PCS

I was hoping the following code would work:

ggplot( hrql.scores, aes( x=PCS, y=..density.. )) +
    geom_histogram(fill="cornsilk",colour="grey35",binwidth=5) +
    geom_density() + 
    geom_density( apdj, aes( x=PCS ) ) + 
    geom_density( health.studio, aes( x=PCS ))

But I get the error Error: ggplot2 doesn't know how to deal with data of class uneval

How would I achieve a density plot of the total data set overlaid with the density plots of the subsets?

Upvotes: 1

Views: 701

Answers (1)

tonytonov
tonytonov

Reputation: 25638

The help page for ?geom_density states that the first argument is mapping, not data. So the correct usage will be

ggplot(hrql.scores, aes(x=PCS, y=..density..)) +
    geom_histogram(fill="cornsilk", colour="grey35", binwidth=5) +
    geom_density() + 
    geom_density(data = apdj) + 
    geom_density(data = health.studio)

Note that there is no need for additional aes mapping, since it is inherited from the top ggplot call.

Upvotes: 1

Related Questions