简体   繁体   中英

Stacked bar in ggplot2, with 2 series of bars (different columns)

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.

在此处输入图像描述


Closest Attempt

I still didn't get the chart that I wanted, but this is the closest that I have:

  1. Did to grouped sub-datasets:
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"
  1. Bound them together:
sub_both <- rbind(sub_b, sub_c)
  1. Made a facetted graph:
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.

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")

在此处输入图像描述

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")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM