Reputation: 1285
Dataset:
I have a dataset as the following: http://www.sharecsv.com/s/786597b1557929e190edf69a46f1dec4/example.csv
Three columns, with YES/NO answers on each.
Problem:
I need to make a stacked bar chart, where A is the horizontal axis. I need two have two stacked bars side by side (one for B column data, one for C column data).
I tried grouping the data as follows, but it doesn't produce the outcome I need:
sum_data <- wsheet %>% group_by(A, B, C) %>% summarise(count = n())
I need both B and C summarised only in terms of A, to be able to put it in the plot.
The following is the incorrect plot I am achieving. I basically need another stacked column for C besides B, for each value of A.
I still didn't get the chart that I wanted, but this is the closest that I have:
sub_b <- wsheet %>% group_by(A, B) %>% summarise(count = n())
colnames(sub_b) <- c("A", "value", "count")
sub_b$measure <- "B"
sub_c <- wsheet %>% group_by(A, C) %>% summarise(count = n())
colnames(sub_c) <- c("A", "value", "count")
sub_c$measure <- "C"
sub_both <- rbind(sub_b, sub_c)
ggplot(sub_both) +
geom_bar( aes(x = A, y = count, fill = value), stat = "identity") +
facet_wrap(~measure)
What did I wanted?
To have B and C bars side by side, instead of facetted.
Upvotes: 1
Views: 514
Reputation: 39595
Update code:
#Read data
wsheet <- read.csv('example.csv')
#Data transform
sub_b <- wsheet %>% group_by(A, B) %>% summarise(count = n())
colnames(sub_b) <- c("A", "value", "count")
sub_b$measure <- "B"
sub_c <- wsheet %>% group_by(A, C) %>% summarise(count = n())
colnames(sub_c) <- c("A", "value", "count")
sub_c$measure <- "C"
#Create variables
sub_both <- rbind(sub_b, sub_c)
sub_both$var <- paste0(sub_both$A,'.',sub_both$measure)
#Plot
ggplot(sub_both) +
geom_bar( aes(x = var, y = count, fill = value), stat = "identity")
Upvotes: 2
Reputation: 1708
Something like this? Edited to use facet_wrap
.
library(tidyverse)
wsheet <- data.frame(stringsAsFactors=FALSE,
A = c("YES", "YES", "NO", "YES", "NO", "YES", "NO", "YES"),
B = c("NO", "YES", "NO", "YES", "NO", "YES", "NO", "YES"),
C = c("YES", "YES", "NO", "YES", "YES", "NO", "YES", "NO"))
df <- wsheet %>%
pivot_longer(-A, names_to = "letter", values_to = "yn") %>%
group_by(letter) %>%
count(yn)
ggplot(df, aes(yn, n, fill = yn)) +
geom_col(position = "dodge") + facet_wrap(~letter) +
labs(x = NULL, fill = NULL) +
theme(legend.position = "none")
Upvotes: 1