Reputation: 194
I want to display data on a stacked bar chart.
The bins will be category "A", "B", "C".
Each bar will be broken into the counts for Active(1) or notActive (0), and show the counts.
Im really struggling with it. Ive gotten close with ggplot but would appreciate some examples to help me see where im going wrong.
isActive <- c(1,0,1,1,0,1,1,1,0)
category <- c('A','B','A','C','C','B','B','C','A')
df <- data.frame(category, isActive)
df
category isActive
1 A 1
2 B 0
3 A 1
4 C 1
5 C 0
6 B 1
7 B 1
8 C 1
9 A 0
Upvotes: 2
Views: 64
Reputation: 2715
How about this?
g <- ggplot(df, aes(factor(category), fill = factor(isActive)))
g + geom_bar() # Stacked
g + geom_bar(position = "dodge") # Side-by-side
We can also show the counts using geom_text
. For example:
g + geom_bar(position = "dodge") + geom_text(stat='count', aes(label=..count..), position = position_dodge(width = 1))
These plots are also fairly quick to do with base graphics:
barplot(with(df, table(isActive, category)))
barplot(with(df, table(isActive, category)), beside = TRUE)
Upvotes: 1