简体   繁体   English

如何在ggplot2中向密度添加两个分布

[英]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. 我想在ggplot2的相同分布中添加两组保龄球得分,但是我在每个组中没有相同数量的观察值,但是我想将它们相互绘制。 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. 问题在于,您要将单个geom_density图层添加到具有不同美学geom_density两个不同图(m和n)中。

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. 其次,首先为kenny绘制一个geom_density图层作为美学,然后为另一个美学(即组)添加geom_density图层。

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

Here is what you obtain: 这是您获得的:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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