简体   繁体   中英

in R - ggplot grouped percentage plot

Given a table:

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

I wish to plot the following plot:

输出

The percentage is calculated as (same condition):

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

Example:

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

Many thanks!

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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