给定一个2x2列联表,其中包含单元格中的计数数字,如何获得具有堆叠百分比的分组条形图?
以下是一些示例代码:
species=c(rep("sorgho" , 1) , rep("poacee" , 1) )
condition=rep(c("normal" , "stress") ,1)
value=abs(rnorm(4 , 0 , 4))
data2=data.frame(species,condition,value)
library(ggplot2)
# Stacked Percent
ggplot(data2, aes(fill=condition, y=value, x=species)) +
geom_bar( stat="identity", position="fill")
但我的数据看起来像是:
A B
Group C 4 5
D 1 2
情节应该告诉我:A组中A的百分比是多少,B组中B的百分比是多少?
感谢。
答案 0 :(得分:1)
你在找这样的东西吗?
library(reshape2)
library(ggplot2)
data <- matrix(c(4, 1, 5, 2), ncol = 2, dimnames = list(c("C", "D"), c("A", "B")))
data_m <- melt(data, varnames = c("Exp", "Obs"), id.vars = "Exp")
ggplot(data_m %>% group_by(Exp) %>%
mutate(perc = round(value/sum(value),2)),
aes(x = Exp, y = perc,
fill = Obs, cumulative = TRUE)) +
geom_col() +
geom_text(aes(label = paste0(perc*100,"%")),
position = position_stack(vjust = 0.5))