我已经在PC上安装了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 =类型,x =基因型,填充=类型)+ geom_bar(stat =“ identity”)+: 二进制运算符的非数字参数
您能帮我解决错误吗?
答案 0 :(得分:2)
是吗?
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())
答案 1 :(得分:1)