R ggplot2中具有百分比的堆叠条形图,用于从头开始分类变量

时间:2019-01-17 13:12:26

标签: r ggplot2

我已经在PC上安装了ggplot2 3.1.0。我的原始数据看起来像(长数据帧的简短示例):

structure(list(genotype = c("A", "A", "A", "A", "A", "A", "A", 
"A", "A", "A", "A", "A", "C", "C", "C", "C", "C", "C", "C"), 
    type = c("M", "M", "M", "M", "M", "M", "M", "M", "M", "M", 
    "M", "M", "R", "R", "R", "R", "R", "R", "R")), row.names = c(NA, 
19L), class = "data.frame")

我使用代码获取以下图表:

library(ggplot2)
ggplot(df_test,aes(x=factor(genotype),fill=factor(type)))+geom_bar(stat="count")+xlab("Genotype")

enter image description here

但是现在我需要用百分比代替计数,以显示100%具有基因型的观察值具有M型,而对于基因型C则相同(100%观察属于R型)。我尝试关注该帖子: enter link description here

我的代码是:

ggplot(df,aes(type,x=genotype,fill=type)+geom_bar(stat="identity")+xlab("Genotype")+scales::percent)

但是出现错误: 误差aes(y =类型,x =基因型,填充=类型)+ geom_bar(stat =“ identity”)+:   二进制运算符的非数字参数

您能帮我解决错误吗?

2 个答案:

答案 0 :(得分:2)

是吗?

library(tidyverse)
df<-data.frame(type=c(rep("A",5),rep("C",5)),genotype=c(rep("M",5),rep("R",5)))

    df %>% 
      mutate_if(is.character,as.factor) %>% 
        ggplot(aes(genotype,fill=type))+geom_bar(position="fill")+
      theme_minimal()+
      scale_y_continuous(labels=scales::percent_format())

答案 1 :(得分:1)

enter image description here我使用了NelsonGon提供的解决方案,但使其变得更短了。此外,如果可能的话,我总是尽量避免使用第三方库。所以对我有用的代码是:

ggplot(df_test,aes(x=factor(genotype),fill=factor(type)))+geom_bar(position="fill")+xlab("Genotype")+scale_y_continuous(labels=scales::percent_format())