修改百分比' ggplot2中geom_bar的格式

时间:2016-03-31 06:25:59

标签: r ggplot2 geom-bar

我试图让geom_bar将计数除以一个归一化因子而不是除以sum(.. counts ..),例如。

n=200
df = data.frame(let = letters[sample(1:26,n,replace=TRUE)],
    cat=letters[sample(1:2,n,replace=TRUE)],
    norm = as.integer(1+round(runif(n)*10))

d <- ggplot(df, aes(let,fill=cat)) +
    geom_bar(aes(y = ((..count..)/sum(..count..))),position='dodge')

enter image description here

相反,我希望除以一个归一化因子:

d <- ggplot(df, aes(let,fill=cat)) +
    geom_bar(aes(y = ((..count..)/norm)),position='dodge')

但这会产生错误:

> d
Error in (count)/norm : non-numeric argument to binary operator

这只是一个玩具的例子。我的实际代码有一个不同的错误,我还没有复制:

> ggplot(droplevels(dfR[keep,]), aes(x=loc_breakBinned,fill=amalgamated_group) ) + 
     geom_bar(aes(y = ((..count..)/subject_count_ASDvTD)),position='dodge')
Error in eval(expr, envir, enclos) : 
  object 'subject_count_ASDvTD' not found

ggplot2坚持认为subject_count_ASDvTD不是dfR的一部分,但快速查看表明它显然是:

> str(dfR[keep,c('amalgamated_group','loc_breakBinned','subject_count_ASDvTD')])
'data.frame':   3694 obs. of  3 variables:
 $ amalgamated_group   : Factor w/ 6 levels "ASD","CONTRAST",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ loc_breakBinned     : Factor w/ 18 levels "pos:(10.7,12.8]_totExonD:(-0.00822,1.64]",..: 14 1 8 8 14 4 8 13 8 14 ...
 $ subject_count_ASDvTD: int  213 213 213 213 213 213 213 213 213 213 ...

这里发生了什么?为什么gant不能看到subject_count_ASDvTD

注意:同样的错误来自

ggplot(droplevels(dfR[keep,]), aes(x=loc_breakBinned,fill=amalgamated_group,y = ((..count..)/subject_count_ASDvTD) ) ) + 
    geom_bar(position='dodge')

1 个答案:

答案 0 :(得分:0)

解决方案是在aes中定义变量。感谢@aosmith帮助我解决这个问题。上面代码的更正版本可以在下面找到:

d <- ggplot(df, aes(let,fill=cat,norm=norm)) +
    geom_bar(aes(y = ((..count..)/norm)),position='dodge')

enter image description here

更复杂的实际代码:

ggplot(droplevels(dfR[keep,]), aes(subject_count=subject_count_ASDvTD,x=loc_breakBinned,fill=amalgamated_group,y = ((..count..)/subject_count) ) ) + 
    geom_bar(position='dodge')