Bradford
Bradford

Reputation: 4193

How do I create a stacked histogram w/ ggplot2?

I want to create a stacked histogram showing canceled == TRUE on bottom and canceled == FALSE on top. I can't seem to figure it out, though. Any ideas how I can do this with ggplot2, while maintaining the facet wrap around source?

Here's what I currently have:

ggplot(data, aes(x=days, fill="canceled")) +
    geom_histogram(binwidth=1, position="stack") +
    facet_wrap(~source, ncol=2, scale="free_y") +
    coord_cartesian(xlim=c(0, 21))

My data:

days,source,canceled
1,ABC,TRUE
1,ABC,FALSE
1,ABC,TRUE
2,ABC,FALSE
2,XYZ,FALSE

Upvotes: 3

Views: 5203

Answers (3)

stevec
stevec

Reputation: 52228

For anyone else arriving here via google looking for a really simple example of how to do a stacked histogram using ggplot2:

ggplot(diamonds, aes(price, fill = cut)) +
  geom_histogram(binwidth = 500)

enter image description here

More info here

Upvotes: 6

Didzis Elferts
Didzis Elferts

Reputation: 98429

As you need to get different fill values by variable canceled then it should be used without quotes. To get stacking in reverse order you can use argument order= and set negative for canceled.

ggplot(data, aes(x=days, fill=canceled,order=-canceled)) +
  geom_bar(binwidth=1, position="stack") +
  facet_wrap(~source, ncol=2, scale="free_y") +
  coord_cartesian(xlim=c(0, 21))

Upvotes: 2

stachyra
stachyra

Reputation: 4593

Well, you should at least start by removing the quote marks from around the word "canceled" in the ggplot command. This results in both the TRUE and FALSE values being colored differently and stacked on top of one another, which is better than what you had before, however, it still stacks TRUE on top and FALSE on bottom, the reverse of what you asked for. I'm not sure how to control the stacking order (you are, after all, presumably using ggplot2 in the first place in order to delegate away a lot of those detailed low-level display decisions) but this at least solves half of your problem. My very slightly modified version of your code and the displayed result are appended below. ggplot results for histogram stacking example

library(ggplot2)

days <- c(1, 1, 1, 2, 2)
source <- c("ABC", "ABC", "ABC", "ABC", "XYZ")
canceled <- c(TRUE, FALSE, TRUE, FALSE, FALSE)

data <- data.frame(days, source, canceled)

print(ggplot(data, aes(x=days, fill=canceled)) + 
             geom_histogram(binwidth=1, position="stack") +
             facet_wrap(~source, ncol=2, scale="free_y") +
             coord_cartesian(xlim=c(0, 21)))

Upvotes: 3

Related Questions