1

I would like to plot one bar on the top of the other one in R. First the count of all the elements having 0, then the count of all the elements having 1, on top of it.

I tried this piece of code in R:

library(ggplot2)

var <- c(0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0)


ggplot(data.frame(var), aes(factor(var), fill=factor(var))) + geom_bar(stat="count", position="stack")

but it generated this plot:

enter image description here

Which is not what I want. I would like to get something like this (I made it with KolourPaint):

enter image description here

Any suggestion on how to do that? Thanks!

DavideChicco.it
  • 3,318
  • 13
  • 56
  • 84
  • 3
    You don't want `var` on the x-axis, you just want a single value. Map `x = factor("my bar")` or something like that. – Gregor Thomas May 08 '18 at 16:32
  • 1
    Possible duplicate of [Stacked bar chart](https://stackoverflow.com/questions/21236229/stacked-bar-chart) – denis May 08 '18 at 16:52

2 Answers2

1

The problem is that you've supplied a variable to the x aesthetic, factor(var), but then from what you say, you don't actually want it there. You can use some dummy variable as x in your aes: a single number or letter, or even just a blank.

Also note that count is the default stat for geom_bar, so you don't have to explicitly supply stat = "count".

library(tidyverse)

var <- c(0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0)

ggplot(data.frame(var), aes(x = "", fill = factor(var))) +
    geom_bar(position = "stack")

Created on 2018-05-08 by the reprex package (v0.2.0).

camille
  • 16,432
  • 18
  • 38
  • 60
0

A quick and dirty solution is to add an additional variable to use on your x axis.

var <- c(0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0)

var=as.data.frame(var)
var$var1=1

ggplot(data.frame(var), aes(factor(var1), fill=factor(var))) + geom_bar(stat="count", position="stack")

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
lmnichols
  • 13
  • 2
  • 1
    Or just directly map to a character vector like `aes(x = 'this is directly mapped', fill = factor(var))` – Axeman May 08 '18 at 16:59