【问题标题】:ggplot - grouped barplot for 2x2 tableggplot - 2x2 表的分组条形图
【发布时间】:2017-10-23 16:51:32
【问题描述】:

给定一个 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 在 C 组中的百分比是多少,B 在 D 组中的百分比是多少?

谢谢。

【问题讨论】:

标签: r ggplot2


【解决方案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))

【讨论】:

  • 可爱!我正是这个意思。非常感谢。您能否将: library(dplyr) 添加到您的代码中?
猜你喜欢
  • 2018-12-03
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多