Combining position_dodge and position_fill in ggplot2

Viewed 2147

What I would like to do is use both the position = "fill" and the position = "dodge" arguments of geom_bar() at the same time somehow. Using some sample data

set.seed(1234)
df <- data.frame(
  Id = rep(1:10, each = 12),
  Month = rep(1:12, times = 10),
  Value = sample(1:2, 10 * 12, replace = TRUE)
)

I'm able to create the following graph

df.plot <- ggplot(df, aes(x = as.factor(Month), fill = as.factor(Value))) + 
  geom_bar(position = "fill") + 
  scale_x_discrete(breaks = 1:12) + 
  scale_y_continuous(labels = percent) +
  labs(x = "Month", y = "Value")

enter image description here

I like the scaling and labeling of this graph but I want to be able to unstack it. However when I do the following

df.plot2 <- ggplot(df, aes(x = as.factor(Month), fill = as.factor(Value))) + 
  geom_bar(position = "dodge", aes(y = (..count..)/sum(..count..))) + 
  scale_x_discrete(breaks = 1:12) + 
  scale_y_continuous(labels = percent) +
  labs(x = "Month", y = "Value")

enter image description here

The bars are in the position and scaling that I want but the y-axis labels represent the percentage of each bar relative to the total count, not the count within each month.

All in all I want the visuals of the second graph with the labeling of the first graph. Is there a relatively easy way to automate this?

1 Answers
Related