ggplot熔化和绘制条形图

时间:2016-05-03 17:42:06

标签: r ggplot2 reshape2

如何绘制条形图,显示var

的每个不同级别的性别百分比

可以按如下方式构建数据:

structure(list(var = structure(c(5L, 5L, 5L, 6L, 5L, 4L, 5L, 
6L, 6L, 6L, 5L, 5L, 5L, 6L, 6L, 5L, 6L, 5L, 6L, 5L), .Label = c("-97:\nMultiple\nResponse", 
"-99:\nRefused", "1:\nDefinitely", "2:\nProbably", "3:\nProbably\nnot", 
"4:\nDefinitely\nnot"), class = "factor"), GENDER = structure(c(1L, 
2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 
1L, 2L, 1L), .Label = c("1: Male", "2: Female", "3: Unknown"), class = "factor")), .Names = c("var", 
"GENDER"), row.names = c(NA, 20L), class = "data.frame")

我希望gender内的条形加起来为100%

1 个答案:

答案 0 :(得分:1)

汇总数据,以便在每个var级别内通过GENDER获取百分比。下面,我使用dplyr在ggplot调用中动态执行此操作。我已调用您的数据框dat

library(dplyr)
library(scales)

ggplot(dat %>% group_by(var, GENDER) %>%
         tally %>%
         mutate(pct=n/sum(n)), aes(var, pct, fill=GENDER)) +
  geom_bar(stat="identity") +
  scale_y_continuous(labels=percent_format())

enter image description here

更新:确保包含空类别:

ggplot(dat %>% group_by(var, GENDER) %>%
         tally %>%
         mutate(pct=n/sum(n))) +
  geom_bar(stat="identity", aes(var, pct, fill=GENDER)) +
  scale_y_continuous(labels=percent_format()) +
  scale_x_discrete(drop=FALSE)