0

Using stat_summary function for getting the sum of each bar and plotting it on to stack bar chart. It is working fine, but somehow it is disturbing the "Aging" table on the right. It is not in order. When I remove the stat_summary code line, it's showing me in order. But I want to show the total of each bar; therefore, I used the stat_summary function.

df3 <- group_by(df, AgeGroup, Org_Name)
totalbarsum <- aggregate(df3$ClaimValue_INR, by=list(Category=df3$Org_Name), FUN=sum) 
dfsecondgraph <- totalsumorg
valueorg <- format(dfsecondgraph$x,big.mark=",",scientific=FALSE)

dfsecondgraph$Aging <- dfsecondgraph$Group.2
datareordersecond <- dfsecondgraph

ggplot(datareordersecond,aes(x = reorder(Category, x,FUN = sum), y = x, fill = Aging))+
  geom_bar(stat = "summary", fun = sum, position = position_stack())+
  geom_col(position = position_stack(reverse = TRUE))+
  geom_text(size = 3, position = position_stack(vjust = 0.5,reverse = TRUE), check_overlap = T,label = valueorg) +
  stat_summary(fun = sum, aes(label = scales::comma (..y..), group = Category),size = 4,vjust = -1, hjust = 0,fontface = "bold",geom = "text")+
  xlab("PAN India Dealerships ") +
  ylab("Claim Value INR") +
  ggtitle("Pending Claims Status : PAN India Dealerships ")+theme(plot.title = element_text(lineheight=3, face="bold", color="black", size=20))+
  scale_y_continuous(labels = comma)+
  theme(axis.text.x = element_text(angle = 0, hjust = 1, size=15))+
  theme(axis.text.y = element_text(angle = 0, hjust = 1, size=15))+
  theme(axis.title.y = element_text(size = rel(1.8), angle = 90))+
  theme(axis.title.x = element_text(size = rel(1.8), angle = 00))+
  scale_fill_manual(values = c("#F8766D", "#7CAE00", "#00BFC4","#C77CFF","#F0E442","#f37735"))+
  coord_flip()

enter image description here

user438383
  • 5,716
  • 8
  • 28
  • 43
  • 1
    Hi! could you provide a minimum reproducible example? (https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You could try to recreate the issue with a builtin dataset such as mtcars or with a small sample of your dataset. This will drastically increase the likelihood of you getting a good and fast answer. – Marcelo Avila Jun 27 '21 at 12:17
  • 1
    Check to see if `datareordersecond$Aging` is a character or factor class. Its legend is ordered alphanumerically, so I think it could be a character class (or a factor with alphanumerically sorted levels). If either is true, you can fix it by mutating the vector into a factor with all its levels provided in the order in the way that you desire. `datareordersecond$Aging <- factor(datareordersecond$Aging, levels=c("0-1 Days", "2-4 Days", "5-7 Days", ...etc., ">30 Days"))` I think it should resolve your problem. As @MarceloAvila said, we can better help you with a reproducible example. – LC-datascientist Jun 27 '21 at 15:52

0 Answers0