繁体   English   中英

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

[英]Stacked barplot with percentage in R ggplot2 for categorical variables from scratch

我已经在我的电脑上安装了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")

在此处输入图片说明

但现在我需要用百分比代替计数,以表明 100% 的基因型观察具有 M 型,基因型 C 相同(100% 观察属于 R 型)。 我试图按照帖子: 在此处输入链接描述

我的代码是:

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

但是得到了错误:错误在 aes(y = type, x = genotype, fill = type) + geom_bar(stat = "identity") + : non-numeric argument to binary operator

你能帮我解决这个错误吗?

是这个吗?

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

在此处输入图片说明 我使用了 NelsonGon 提供的解决方案,但让它更短了一点。 此外,如果可能的话,我总是尽量避免使用第三方库。 所以对我有用的代码是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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