用不同的变量填充和分组条形图

时间:2019-08-13 05:53:32

标签: r ggplot2

我正在尝试创建具有以下特征的多面geom_bar图:

  1. 显示每个问题每个问题的比例
  2. 每个栏的颜色均根据响应
  3. 情节面临问题

我似乎能够满足其中任何两个条件,但不能同时满足所有3个条件。

问题:

是否有一种方法可以使用一个变量进行构面和比例计算,但是根据另一个变量进行颜色/填充?

代码:

df <- data.frame(
  Question = rep(c('A', 'B', 'C'), each = 5),
  Resp     = sample(c('Yes', 'No', 'Unsure', NA), 15, T, c(0.3,0.3,0.3,0.1)),
  stringsAsFactors = F
)

# Plot 1: grouping by question to get the right proportions, but has no colour

ggplot(df, aes(x = Resp, fill = Resp)) +
  stat_count(aes(y = ..prop.., group = Question)) +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_wrap(~ Question)

# Plot 2: grouping by response to get colour, but has wrong proportions

ggplot(df, aes(x = Resp, fill = Resp)) +
  stat_count(aes(y = ..prop.., group = Resp)) +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_wrap(~ Question)

输出:

enter image description here

3 个答案:

答案 0 :(得分:3)

这是“仅限ggplot2”选项:

ggplot(df, aes(x = Resp)) +
  geom_bar(aes(y = ..prop.., group = Question, fill = factor(..x..)), position = "dodge") +
  scale_y_continuous(labels = scales::percent_format()) +
  scale_fill_discrete(name = "Response", labels = c("No", "Unsure", "Yes", "NA")) +
  facet_wrap(~ Question)

enter image description here

答案 1 :(得分:2)

一种方法是计算比例然后绘制。

library(dplyr)
library(ggplot2)

df %>%
  count(Question, Resp) %>%
  group_by(Question) %>%
  mutate(n = n/sum(n) * 100) %>%
  ggplot() + aes(Resp, n, fill = Resp) + 
  geom_col() + 
  facet_wrap(~Question)

enter image description here

答案 2 :(得分:2)

无分面的图

df$n <- 1

df <- df %>% group_by(Question, Resp) %>% summarise(n = sum(n))

ggplot(df, aes(x=factor(Question), y=n, fill=Resp)) + geom_col()

enter image description here

具有刻面的图

df <- df %>% group_by(Question, Resp) %>% summarise(n = sum(n)) %>% mutate(prop = n/5)

ggplot(df, aes(x=factor(Resp), y=prop, fill=Resp)) + geom_col() + facet_wrap(~Question)

enter image description here