heyydrien
heyydrien

Reputation: 981

ggplot why are bars not stacked?

I would like to create a stacked bar graph however my output shows overlaid bars instead of stacked. How can I rectify this?

#Create data
date <- as.Date(rep(c("1/1/2016", "2/1/2016", "3/1/2016", "4/1/2016", "5/1/2016"),2))
sales <- c(23,52,73,82,12,67,34,23,45,43)*1000
geo <- c(rep("Western Territory",5), rep("Eastern Territory",5))
data <- data.frame(date, sales, geo)

#Plot
library(ggplot2)
ggplot(data=data, aes(x=date, y=sales, fill=geo))+
    stat_summary(fun.y=sum, geom="bar") +
    ggtitle("TITLE")

Plot output: GGPLOT stacked bar graph

As you can see from the summarized table below, it confirms the bars are not stacked:

>#Verify plot is correct
>ddply(data, c("date"), summarize, total=sum(sales))
    date  total
1 0001-01-20  90000
2 0002-01-20  86000
3 0003-01-20  96000
4 0004-01-20 127000
5 0005-01-20  55000

Thanks!

Upvotes: 0

Views: 989

Answers (2)

Mark Peterson
Mark Peterson

Reputation: 9560

Alternatively, since your data are already summarized, you could use geom_col (the short hand for geom_bar(stat = "identity")):

ggplot(data=data, aes(x=date, y=sales, fill=geo))+
  geom_col() +
  scale_x_date(date_labels = "%b-%d")

Produces:

enter image description here

Note that I changed the date formatting (by adding format = "%m/%d/%Y" to the as.Date call) and explictly set the axis lable formatting.

If your actual data have more than one entry per period, you can always summarise first, then pass that into ggplot instead of the raw data.

Upvotes: 3

Jon Cardoso-Silva
Jon Cardoso-Silva

Reputation: 990

You have to include position="stack" in your statSummary:

stat_summary(position="stack",fun.y=sum, geom="bar")

Upvotes: 3

Related Questions