ggplot: relative frequencies of two groups

后端 未结 2 1249
生来不讨喜
生来不讨喜 2021-01-01 00:54

I want a plot like this except that each facet sums to 100%. Right now group M is 0.05+0.25=0.30 instead of 0.20+0.80=1.00.

df <- rbind(
    data.frame(g         


        
相关标签:
2条回答
  • 2021-01-01 01:00

    here's another way

    ggplot(df, aes(outcome)) +
        geom_bar(aes(y = ..count.. / sapply(PANEL, FUN=function(x) sum(count[PANEL == x])))) +
        facet_wrap(~gender, nrow=2, ncol=1) 
    
    0 讨论(0)
  • 2021-01-01 01:19

    I usually do this by simply precalculating the values outside of ggplot2 and using stat = "identity":

    df1 <- melt(ddply(df,.(gender),function(x){prop.table(table(x$outcome))}),id.vars = 1)
    
    ggplot(df1, aes(x = variable,y = value)) +
        facet_wrap(~gender, nrow=2, ncol=1) +
        geom_bar(stat = "identity")
    
    0 讨论(0)
提交回复
热议问题