'How to make sure the geom_text graph labels stays at the right place?

#Analysis 5: Find the relationship between mother's occupation and the average of applicants' salary.

ggplot(withSalary, aes(Mjob, fill=as.factor(salary_range)))+
  geom_bar(stat="count", aes(fill=as.factor(salary_range)), position=position_dodge())+
  ggtitle("Applicants' salary group by their mothers' jobs")+
  labs(fill="Mothers' jobs")+
  geom_text_repel(stat='count', aes(label=..count..))

I am doing analysis for my assignment and I encountered an issue after running such code, where the labels would not stay at the correct locations: enter image description here

Is it my RStudio issue here? Or is it the code? btw, geom_text_repel is from ggrepel package and is used to prevent the labels from overlapping on each other.



Solution 1:[1]

I recommend to use geom_text() instead of geom_text_repel(). Here is my code:

geom_text(aes(label = ..count..), 
position=position_dodge(width=0.9),      # center of bars
vjust = -.25     #  above top of bar
).

I recomend you build up a summary table first, then draw the graph. It could help you add other labels easily, such as percentage. Here is my code:

withSalary %>%
  group_by(Mjob, as.factor(salary_range)) %>%
  summarize(count = n(), .groups = "drop_last") %>%
  mutate(freq = count / sum(count)) %>%                             # a summary table include count and pct.
  ggplot(aes(x = Mjob, y = count,fill=as.factor(salary_range))) + 
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label=sprintf('%d (%s)', count,scales::percent(round(freq,1)))), 
  position=position_dodge(width=0.9), vjust = -.25) +               # the label include count and pct
  ggtitle("Applicants' salary group by their mothers' jobs") +
  labs(fill="Mothers' jobs")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1