Stacked barplot with percentage in R ggplot2 for c

2019-09-25 08:19发布

问题:

I've installed ggplot2 3.1.0 on my PC. My raw data look like (short example of the long data frame):

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

I used the code to obtain the following plot :

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

But now i need to substitute the count by percentage, to show that 100% of the observations with genotype have type M and the same for genotype C (100% observations belong to type R). I tried to follow the post: enter link description here

My code was:

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

But got the error: Error in aes(y = type, x = genotype, fill = type) + geom_bar(stat = "identity") + : non-numeric argument to binary operator

Could you please help me to fix the error?

回答1:

Is this it?

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


回答2:

I used solution provided by NelsonGon, but maked it a bit shorter. Besides i always try to avoid of using third party libraries if it's possible. So the code working for me was:

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


标签: r ggplot2