0

I have two dodge bar chart which I have put on top of each other to create this plot.

Groups <- c(1, 2,1,2,1,2)
variable <- c("Yes", "Yes", "Maybe", "Maybe", "No", "No")
value <- c(50,60,70,80,90,100)
df <- data.frame(Groups, variable, value)

Groups <- c(1, 2,1,2,1,2)
variable <- c("Yes*", "Yes*", "Maybe*", "Maybe*", "No*", "No*")
value <- c(5,6,7,8,9,10)
df2 <- data.frame(Groups, variable, value)

ggplot() +
  geom_bar(data=df, aes(x=Groups, y=value, fill=variable),
           stat="identity", position=position_dodge(), alpha=0.2)+
  geom_bar(data=df2, aes(x=Groups, y=value, fill=variable),
           stat="identity", position=position_dodge())

enter image description here

I would like for the opacity/alpha from the plot behind to show in the legend.

I have tried +guides(colour = guide_legend(override.aes = list(alpha = 0.2))) but this does not work.

Thanks.

Alis
  • 80
  • 7

1 Answers1

2

You can use a little trick with after_scale to achieve this. Map fill to the variable in one geom layer, and map color to variable in the second layer, but set the second layer's fill to after_scale(color). This will give you two legends, one for the first data set with its transparency, and the other for the second set, fully opaque. You can call these whatever you like using labs

ggplot(df, aes(Groups, value)) +
  geom_col(aes(fill = variable), position = 'dodge', alpha = 0.2) +
  geom_col(data = df2, aes(color = variable, fill = after_scale(color)),
           position = 'dodge') +
  labs(color = 'df2', fill = 'df1')

enter image description here

If you want everything in a single legend, you can do this in a couple of ways, for example, using a manual fill value with 6 colors, 3 of which have alpha set, or just merging the two legends in the method above using theme tweaks:

ggplot(df, aes(Groups, value)) +
  geom_col(aes(fill = variable), position = 'dodge', alpha = 0.2) +
  geom_col(data = df2, position = 'dodge', size = 0,
           aes(color = variable, fill = after_scale(color))) +
  labs(color = 'key', fill = NULL) +
  guides(fill = guide_legend(order = 2), 
         color = guide_legend(order = 1, 
                   override.aes = list(color = 'white', size = 0.3))) +
  theme(legend.spacing.y = unit(-2, 'mm'),
        legend.title = element_text(vjust = 5))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Thank you for your help. I went with a simpler approach suggested by someone above. I did + scale_fill_manual(values=c("Maybe"= alpha("#7570b3", 0.2),"Maybe*"= alpha("#7570b3", 1),.......and so on... )) – Alis Oct 13 '22 at 14:18
  • @Alis - this is what I meant when I said above 'using a manual fill value with 6 colors, 3 of which have alpha set' – Allan Cameron Oct 13 '22 at 14:22