R ggplot2中具有百分比的堆叠条形图,用于从头开始分类变量 [英] Stacked barplot with percentage in R ggplot2 for categorical variables from scratch

查看:86
本文介绍了R ggplot2中具有百分比的堆叠条形图,用于从头开始分类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 结构(列表(基因型= c("A","A","A","A","A","A","A","A","A","A","A","A","C","C","C","C","C","C","C"),类型= 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),类="data.frame") 

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

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

但是现在我需要用百分比代替计数,以显示100%具有基因型的观测值具有M型,而对于基因型C则相同(100%观测值属于R型).我尝试关注该帖子:我使用了NelsonGon提供的解决方案,但使它略短了一些.此外,如果可能的话,我总是尽量避免使用第三方库.所以对我有用的代码是:

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

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?

解决方案

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中具有百分比的堆叠条形图,用于从头开始分类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆