Reputation: 113
I'm trying to make some stacked bar charts using ggplot2 in R, but no matter what I do my charts always end up being grey.
As a toy example, if I run this:
Year <- c(2015,2015,2015,2015,2016,2016,2017,2017,2017,2017)
Class <- c(2,1,2,3,2,3,1,2,3,2)
Data <- data.frame(Year,Class)
ggplot(Data, aes(Year)) +
geom_bar(aes(fill=Class))
I get the following (very grey) chart:
Every ggplot tutorial I have found suggests that I should get something more colourful that looks like a stacked bar chart. Any suggestions? I am a complete novice, so there's a fair chance it's my fault.
Upvotes: 2
Views: 2683
Reputation: 947
use stat='identity'
and a table of counts per group. Then use position='stack'
to stack bars while preserving grouping information based on the Class
Default stat='count'
, which means ggplot counts the number of times each value (here, Year), occurs, but it does not take into account any other grouping variables. stat='identity'
means ggplot reads the values as actual bar heights.
melt()
from reshape2
reformats the table()
output into long format which ggplot is able to read
library(ggplot2)
library(reshape2)
Year <- c(2015,2015,2015,2015,2016,2016,2017,2017,2017,2017)
Class <- c(2,1,2,3,2,3,1,2,3,2)
Data <- data.frame(Year,Class)
Data2 <- melt(table(Data))
ggplot(mpg, aes(class)) +
geom_bar(aes(fill = drv))
ggplot(Data2, aes(x=Year, y=value)) +
geom_bar(aes(fill = as.factor(Class)), position='stack', stat='identity')
Upvotes: 2