Search code examples
rggplot2geom-bargeom-text

Geom_Text not positioning vjust label over Geom_Bar


I was following code from this post but it is not working the same for me. Here's my code and screenshot below. Can you help me center the label with spacing just above the bar?

Click Here - Screenshot

p <- ggplot(data=mrc, aes(x = Year, y = Total, fill = Year)) + 
  geom_bar(stat="identity", position = "dodge") +
  geom_text(
        aes(x = Year, y = Total, label = Total),
        position = position_dodge(width = 1),
        vjust = -0.5, size = 3
  ) +
  theme_bw() +
  scale_fill_manual(values = c("#115740","#B9975B","#D0D3D4","#F0B323")) +
  theme(axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        legend.position = "none",
        plot.title = element_text(hjust = 0.5, face = "bold", colour = "#B9975B")) +
  ggtitle("Petitions") 

ggplotly(p)

Solution

  • The issue here is ggplotly. One solution is to use style(textposition = "top").

    Recreating your data:

    mrc <- data.frame(Year = c("2015-16", "2016-17", "2017-18", "2018-19"),
                      Total = c(225, 461, 471, 230),
                      stringsAsFactors = FALSE)
    

    Running the first section of your code to generate p:

    p
    

    enter image description here

    All good. But the result using ggplotly:

    ggplotly(p)
    

    enter image description here

    Adding style():

    ggplotly(p) %>% style(textposition = "top")
    

    enter image description here