【问题标题】:Normalizing y-axis in density plots in R ggplot to proportion by group将R ggplot中密度图中的y轴标准化为按组的比例
【发布时间】:2017-12-19 06:49:52
【问题描述】:

我的问题与

非常相似

Normalizing y-axis in histograms in R ggplot to proportion by group

除了,我需要密度图,我希望将 y 轴作为比率,例如每 1000 名患者的 x 计数。

我有多组不同大小的数据,我希望每个比例都是相对于其组大小而不是总大小。

为了更清楚,假设我在一个数据框中有两组数据

示例数据:

dataA<-rnorm(10000,3,sd=2)
dataB<-rnorm(40000,5,sd=3)
bp_combi<-data.frame(dataset=c(rep('A',length(dataA)),rep('B',length(dataB))),
                     value=c(dataA,dataB))

我可以将分布相对于总大小绘制在一起,但不能相对于相对大小。

combi_dens = ggplot(bp_combi, 
                    aes(x=value, 
                        number_of_cases=nrow(bp_combi),
                        y=(..count..)/number_of_cases*1000, fill=dataset)) +
               geom_density(bw = 1, alpha=0.4, size = 1.5 )

是否可以根据每个组的大小来设置它?

谢谢!

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    对于那些仍然感兴趣的人。答案相当简单。首先创建一个具有相对组大小的单独列,并在 ggplot 中使用该列。

    unique_episodes = bp_combi %>% group_by(dataset) %>% count(dataset)
    data2 = merge(x = bp_combi, y = unique_episodes, by = "dataset", all.x = TRUE)
    
    
    combi_dens = ggplot(bp_combi, 
                        aes(x=value,,
                            y=(..count..)/n*1000, fill=dataset)) +
      geom_density(bw = 1, alpha=0.4, size = 1.5 )
    

    【讨论】:

    • 不错的答案!也许您需要稍微编辑您的答案,以便提及您使用的是原始数据集 (bp_combi) 而不是您创建的 data2。基本上,在您的回答中,data2 不是必需的,因为ggplot2 将自行计算 n。我说的对吗?
    猜你喜欢
    • 2014-04-06
    • 2012-07-30
    • 1970-01-01
    • 2019-04-13
    • 2018-11-25
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多