首页 文章

条形图显示因子变量占一定值的比例

提问于
浏览
4

我有一个类似的数据集

df <- data.frame(cbind(
  c(rep.int(x = 0, times =7), 1:3), 
  c(1, 1, 1, 0, 1, 0, 1, 1, 0, 0),
  c(1:3, 1:3, 1:3, NA)))
names(df) <- c("cars", "sex", "status")
df$sex <- factor(df$sex, labels = c("male", "female"))
df$status <- factor(df$status, labels = c("bad", "ok", "good"))
df$car <- (df$cars > 0) # Person has at least 1 car

我想使用ggplot2制作一个具有以下特征的刻面条形图:

  • 由分类变量(本例中的性别和状态)构成的分面

  • 每个面板每个级别包含一个条形(例如"sex"的男性和女性)

  • 每个条形显示该因子水平的观察总数中有多少百分比,至少有1辆汽车(例如至少有1辆汽车的男性百分比)

我怎样才能在ggplot2中顺利完成这项工作? (或者,您是否有更好的建议如何以图形方式表示这些比例?)

1 回答

  • 4
    library(ggplot2)
    
    df.long = melt(df, measure.vars=c('sex', 'status'))
    df.long.summary = ddply(df.long, .(variable, value), summarize, cars=sum(cars > 0) / length(cars))
    
    ggplot(data=df.long.summary, aes(x=value, y=cars)) +
      geom_bar(stat='identity') +
      facet_wrap(~variable, scales='free_x') +
      scale_y_continuous(formatter='percent')
    

    enter image description here

    (顺便说一句,它在 ggplot2 的下一个版本中甚至更简单,因为不需要手动计算摘要,因为您可以自动将绘图范围限制为摘要而不是原始数据)

相关问题