-5

I have a data-set as below:

A   B   C
1   1   1
0   1   1
1   0   1
1   0   1

I want to have a stack bar chart that shows percentage of 1 and 0 in each column next to other column all in one figure.

Sajjad
  • 67
  • 2
  • 8

2 Answers2

3

There are several steps you need to take:

  • calculate how many zeros and ones are for each variable
  • calculate relative percentage (you don't define this in your question
  • reflow data from wide to long (use tidyr::gather)
  • plot using ggplot's geom_bar
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
1

First you need to tidy your data

library(tidyr)

A = c(1,0,1,1)
B = c(1,1,0,0)
C = c(1,1,1,1)

data = data.frame(A,B,C)
data = gather(data, key = type, value = val)

Then compute your statistics

library(dplyr)
perc = group_by(data, type) %>% summarise(perc = sum(val)/length(val))

To finish plot them

library(ggplot2)
ggplot(perc) + aes(x = type, y = perc) + geom_bar(stat = "identity")
JRR
  • 3,024
  • 2
  • 13
  • 37