【问题标题】:Stacked barplot with percentage in R ggplot2 for categorical variables from scratchR ggplot2中从头开始分类变量的带有百分比的堆叠条形图
【发布时间】:2019-01-17 13:12:26
【问题描述】:

我已经在我的电脑上安装了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 型)。我试着关注这个帖子: enter link description here

我的代码是:

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") + 中的错误: 二元运算符的非数字参数

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

【问题讨论】:

  • 使用dput 添加样本数据而不是图像。

标签: r ggplot2


【解决方案1】:

是这个吗?

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】:

    我使用了 NelsonGon 提供的解决方案,但缩短了一点。此外,如果可能的话,我总是尽量避免使用第三方库。所以对我有用的代码是:

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

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2015-01-16
      • 2018-12-09
      相关资源
      最近更新 更多