简体   繁体   中英

How to add two distributions to a density in ggplot2

I want to add two sets of bowling scores onto the same distribution in ggplot2, I don't have the same amount of observations in each group but I would like to plot them on top of eachother. Below is the code I have.

    m <- ggplot(bowling, aes(x = as.numeric(Kenny)))
    n <- ggplot(bowling, aes(x= as.numeric(Group)))
    m + n geom_density()

and this is the error.

    Error in p + o : non-numeric argument to binary operator
    In addition: Warning message:
    Incompatible methods ("+.gg", "Ops.data.frame") for "+" 

I just want to plot them on top of eachother but I can't figure out what the problem is.

The problem is that you're adding a single geom_density layer to two different plots (m and n) that have different aesthetic mappings.

Here is a potential solution, if I understood your question correctly.

First, creating a small sample dataset

kenny <- rnorm(100, 20, 2)  
group <- rnorm(100, 15, 2)  
bowling <- data.frame(kenny, group)

Second, plotting first a geom_density layer for kenny as an aesthetic, and then adding a geom_density layer for a different aesthetic, namely group.

ggplot(bowling, aes(x = kenny)) +  
geom_density() + geom_density(aes(x=group), colour="red")

Here is what you obtain:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM