0

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)
markus
  • 25,843
  • 5
  • 39
  • 58
Willy
  • 13
  • 4
  • 2
    Please share your data (`mrc`) to make it reproducible – Tung Jul 02 '19 at 21:32
  • Unrelated, but you can simplify your code by using `geom_col()` instead of `geom_bar(stat="identity", position = "dodge")` and omitting the `position = ` argument to `geom_text`. – neilfws Jul 02 '19 at 23:01
  • @neilfws Thanks for the tip mate. Why use geom_col() instead? And why omit position? – Willy Jul 03 '19 at 19:19
  • @Willy less typing :) and position makes no difference in this case. – neilfws Jul 03 '19 at 20:49

1 Answers1

1

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

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Thank you so much! I didn't even think that ggplotly was the cause of the issue. Could you explain your thought process for finding the culprit and the solution? – Willy Jul 03 '19 at 19:27
  • @Willy I just ran the standard ggplot first, then inspected the difference after ggplotly. I guess I’ve seen previous questions where ggplotly has caused issues too, so I’m primed to be suspicious. – neilfws Jul 03 '19 at 20:52