Home > Enterprise >  How do I neatly align my stacked barchart labels?
How do I neatly align my stacked barchart labels?

Time:12-20

I have my labels roughly aligned to each side of my stacked bar chart. The problem is that they look like a mess because they aren't right and left justified on either side of the bar. How do I fix this so that they look professional?

df3 <- data.frame(
  Label = c("Dasher", "Dancer", "Comet", "Cupid", "Prancer", "Blitzen", "Rudolph"),
  Amount = c(650.01, 601.01, 340.05, 330.20, 260.01, 250.80, 10.10)
)

# Sort order
level_order <- df3 %>% 
  arrange(desc(Amount))

ggplot(level_order, aes(fill=fct_inorder(Label), y=Amount, x=""))   
               geom_bar(position="stack", stat="identity", width = 0.55)  
               scale_fill_brewer(palette = "Blues", direction = -1)  
               theme_void()  
               geom_text(aes(label = paste0("$", Amount)),
                         position = position_stack(vjust = 0.5),
                         hjust = -3.1,
                         size = 5)  
               geom_text(aes(label = Label),
                         position = position_stack(vjust = 0.5),
                         hjust = 5,
                         size = 5)  
               theme(legend.position = "none")  
               theme(plot.title = element_text(size = 50, hjust = .5, vjust = 0))  
               ggtitle("Food Costs by Reindeer")

enter image description here

CodePudding user response:

Try fixing the x co-ordinate in the call to geom_text and managing alignment with hjust...

df3 <- data.frame(
  Label = c("Dasher", "Dancer", "Comet", "Cupid", "Prancer", "Blitzen", "Rudolph"),
  Amount = c(650.01, 601.01, 340.05, 330.20, 260.01, 250.80, 10.10)
)


library(ggplot2)
library(dplyr)
library(forcats)

level_order <- df3 %>% 
  arrange(desc(Amount))

ggplot(level_order, aes(fill=fct_inorder(Label), y=Amount, x=""))   
  geom_bar(position="stack", stat="identity", width = 0.55)  
  scale_fill_brewer(palette = "Blues", direction = -1)  
  theme_void()  
  geom_text(aes(x = 1.3, label = paste0("$", Amount)),
            position = position_stack(vjust = 0.5),
            hjust = 0,
            size = 5)  
  geom_text(aes(x = 0.6, label = Label),
            position = position_stack(vjust = 0.5),
            hjust = 0,
            size = 5)  
  theme(legend.position = "none")  
  theme(plot.title = element_text(size = 50, hjust = .5, vjust = 0))  
  ggtitle("Food Costs by Reindeer")

Created on 2021-12-19 by the Solution Result

  • Related