1

I followed some code example here to try and use both stack and dodge with a bar plot. I can achieve the stack and dodge, but when I do I do not have color. When I add the fill to the main ggplot2 call I get the desired colors, but no longer get the stack.

Here is some reproducible code.

library(ggplot2)
library(dplyr)
Weeks_Years <- c(rep("42 - 2021" , 5) , rep("42 - 2020" , 5) , rep("43 - 2021" , 5) , rep("43 - 2020" , 5))
Risk_Category <- rep(c("A","B","C","D","E") , 4)
Exp_premium <- abs(rnorm(20 , 0 , 20))
newdata <- data.frame(Weeks_Years,Risk_Category,Exp_premium)
newdata$year = as.factor(ifelse(newdata$Weeks_Years == "42 - 2020", 2020,
                       ifelse(newdata$Weeks_Years == "43 - 2020", 2020, 2021)))

Below I can demonstrate how to use the position argument; however, there is no longer stacked columns.

#color, no stack
newdata %>% 
  group_by(Week, Year) %>% 
  ggplot(aes(y=Exp_premium, x=Weeks_Years, fill = Risk_Category)) + 
  geom_col(data = . %>% filter( Year=="2020"), position = position_dodge(width = 0.9), alpha = 1, aes(fill = Risk_Category)) + #adjust dodge to manipulate width betweeen years
  geom_col(data = . %>% filter( Year=="2021"), position = position_dodge(width = 0.9), alpha = 0.4, aes(fill= Risk_Category))

output enter image description here

Below I can demonstrate how to use geom_bar and delineate between the years of acquired data, stack as intended, but what I cannot do is include a position argument because if I do the plot is displayed as the example above.

#color, stack, and intended alpha to delineate between years. But no position argument.
newdata %>%
ggplot(aes(y=Exp_premium, x=Weeks_Years, fill = Risk_Category)) +
  geom_bar(stat='identity', aes(alpha = Year)) +
  labs(x='Week / Year') +
  scale_alpha_manual(values = c(1, 0.5), guide = FALSE) #set alpha 

output enter image description here

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
Aswiderski
  • 166
  • 9

0 Answers0