Reputation:
When I do the following in R, I get a very strange bar chart
a <- c('A', 'B','C','A','B', 'A','C')
b <- rep(2015, 7)
c <- c(5, 32, 7, 1, 74, 2, 23)
d <- data.frame(a,b,c)
ggplot(data=d, aes(x=b, y=c, fill=a)) + geom_bar(stat="identity")
I get the following chart
I have 3 red areas instead of one, 2 green areas and 2 blue areas.
Why does the same color not add up to one single area?
Upvotes: 1
Views: 407
Reputation: 13139
ggplot determines the stacking order based on the order of your data. So you can summarize your data like @Mateusz1981 did, but another approach is to sort your data by your fill variable by using order:
ggplot(data=d, aes(x=factor(b), y=c, fill=a, order=a)) +
geom_bar(stat="identity")
Upvotes: 2
Reputation: 1867
directly
ggplot(data=d, aes(x=factor(b), y=c, fill = factor(a))) + stat_summary(fun.y = sum, aes(group = a), geom = "bar", position = "stack")
or with dplyr
library(dplyr)
library(ggplot2)
d <- d %>% group_by(a, b) %>% summarise(s = sum(c))
ggplot(data=d, aes(x=factor(b), y=s, fill=a)) + geom_bar(stat="identity")
Upvotes: 1