0

I am trying to label columns with geom_text() on a geom_col(). But, the labels (numbers) doesn't labeled the columns properly. It seems that the hjust values are different from each other.

Dataset: https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-12-13/state_retail.csv

My Code:

state_retail %>% 
  group_by(subsector) %>% 
  summarise(avg_change_yoy = mean(change_yoy, na.rm = TRUE),
            avg_change_yoy_se = mean(change_yoy_se, na.rm = TRUE),
            total = sum(avg_change_yoy + avg_change_yoy_se)) %>% 
  pivot_longer(cols = c("avg_change_yoy", "avg_change_yoy_se"),
               names_to = "avgs",
               values_to = "values") %>% 
  arrange(desc(total)) %>% 
  slice_head(n = 12) %>% 
  ggplot(aes(values, reorder(avgs, values), fill = subsector, color = subsector)) +
  geom_col(position = "dodge") +
  scale_y_discrete(labels = c(
    "avg_change_yoy" = "Average Change Yoy",
    "avg_change_yoy_se" = "Average Change Yoy Se"
  )) +
  theme(legend.position = "bottom") +
  #print value for each bar as well
  geom_text(aes(label = format(round(values, digits = 2), big.mark = ",")), hjust = "inward", 
            size = 4, color ="white", position = position_dodge(1))

As you can see in the chart below, some labels are at the top of the column, some in the middle and some at the bottom.

How can I arrange these values to be centered on geom_col()? I want all labels to be in the middle like the red columns.

Note: Also, one of the labels doesn't even appear in the column. In the second to last column.

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
Ali Osman
  • 17
  • 4
  • Try with `position = position_dodge(.9)` in `geom_text`. `.9` is the default width by which the bars are dodged. – stefan Dec 16 '22 at 10:53
  • Possible duplicate: [ggplot: geom_text does not center-align above geom_col()](https://stackoverflow.com/questions/64091110/ggplot-geom-text-does-not-center-align-above-geom-col) – stefan Dec 16 '22 at 11:01
  • 1
    It really works! Thanks for the help. However, why one of the labels (In the second to last column.) does not fit "inward" to the column? – Ali Osman Dec 16 '22 at 11:03
  • You could fix that by using `hjust=1`. – stefan Dec 16 '22 at 11:14
  • 1
    The graphic looks very nice. Thanks again. – Ali Osman Dec 16 '22 at 11:21

0 Answers0