在R - ggplot分组百分比图

时间:2017-10-30 21:03:39

标签: r plot ggplot2

给出一张表:

Feature value   Condition   Sex
A       6       1           M
A       4       2           M
A       10      3           M
Aneg    1       1           M
Aneg    2       2           M
Aneg    6       3           M
A       2       1           F
A       3       2           F
A       4       3           F
Aneg    5       1           F
Aneg    6       2           F
Aneg    9       3           F

我想绘制以下情节:

Output

百分比计算为(相同条件):

p = A*(100/(A+Aneg))

示例:

p = 6*(100/(6+1))=85%

非常感谢!

1 个答案:

答案 0 :(得分:1)

library(tidyr)
df2 <- df %>% 
    spread(Feature, value) %>% 
    mutate(p = A*(100/(A+Aneg)))

#   Condition Sex  A Aneg        p
# 1         1   F  2    5 28.57143
# 2         1   M  6    1 85.71429
# 3         2   F  3    6 33.33333
# 4         2   M  4    2 66.66667
# 5         3   F  4    9 30.76923
# 6         3   M 10    6 62.50000

library(ggplot2)
ggplot(df2, aes(Sex, p, fill=factor(Condition))) + 
    geom_bar(stat="identity", position="dodge")

enter image description here