0

I was trying to put the labels to all the bars on the plot, but some of them keep being under the bars. What should I edit in the code? enter image description here

ggplot(data, aes(x = year,y = value)) + 
  geom_text(aes(label=value),  vjust=-3.5, size=3.5)+
  geom_bar(aes(fill = variable), stat = "identity",position = "dodge")+
  scale_x_continuous(breaks = unique(data$year))+
  ylab("Number of candidates")+
  theme(axis.title.x=element_blank())+
  scale_fill_discrete(name="",
                      labels=c("All", "Female"))
  • 1
    Layers are drawn in the order you supply them. You've drawn a bar layer after, and thus on top of, a text layer – camille Dec 04 '19 at 20:59

1 Answers1

1

You need to add position_dodge to your geom_text in order to follow the position_dodge of the geom_bar.

Here, I took the example of the iris dataset that I reshape using pivot_longer

library(tidyverse)
ir_df <- iris %>% group_by(Species) %>% 
  summarise(Mean_Length = mean(Sepal.Length), Mean_Width = mean(Sepal.Width)) %>% 
  pivot_longer(., -Species, names_to = "Variables", values_to = "Value")

library(ggplot2)
ggplot(ir_df, aes(x = Species, y = Value, fill = Variables))+
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_text(aes(label = Value), vjust = -3.5, position = position_dodge(width = 1))

enter image description here

If you don't succeed to adapt this code to your dataset, please consider to provide a reproducible example of your dataset

Community
  • 1
  • 1
dc37
  • 15,840
  • 4
  • 15
  • 32