Reputation: 25
I have a ggplot barplot that looks like this:
But the bonus bar is overlapping the account recharge bar. I want these bars to sum op so the first bars for example need to be equal to 152 on the y-axis. Does anyone know how to achieve this? Working with facets is not ideal in my situation. I have to plot it in one graph.
This is an example of (a part of) my data:
data <- data.frame(
sale_year_month = c("2020-04", "2020-04", "2020-04", "2020-05", "2020-05", "2020-05"),
spending_type = c("Account recharge", "Bonus", "Account use", "Account recharge", "Bonus", "Account use"),
spending = c(140, 12, 53, 222, 16, 224.50),
grp = c(0,0,1,0,0,1)
This is the code I used to plot my ggplot:
ggplot(spending_aalst_totaal, aes(x = sale_year_month, y = spending, group = grp, fill = spending_type)) +
geom_col(position = position_dodge(width = 0.8), width = 0.7) +
geom_text(aes(label = spending), position = position_dodge(width = 0.9), vjust = -0.5, color = "black", size = 4) +
scale_fill_manual(values = c("darkseagreen", "firebrick2", "darkseagreen4")) +
theme(axis.text.x = element_text(size = 10, angle = 45))
Thank you!
Upvotes: 1
Views: 335
Reputation: 39595
One way using facets but it needs a group first so that bars can be arranged properly:
library(dplyr)
library(ggplot2)
#Code
data %>%
mutate(Var=ifelse(spending_type %in% c('Account use'),'A','B')) %>%
ggplot(aes(x=Var,y=spending,
fill=factor(spending_type)))+
geom_bar(stat = 'identity')+
facet_wrap(.~sale_year_month,strip.position = 'bottom')+
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
strip.placement = 'outside',
strip.background = element_blank(),
panel.spacing = unit(0,'lines'))+
labs(fill='Var')
Output:
Upvotes: 0