簡體   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