[英]R ggplot2 stacked barplot by percentage with several categorical variables
[英]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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.