How to center the text of a label made with geom_label() whose vertical position was changed with vjust? (ggplot2 package)

Viewed 325

I plotted columns with the ggplot2 package and the geom_col() function. I put a label at the top of each column with the respective values with the geom_label() function. Inside the geom_label() function I modified the text size (size = 3) and label position (vjust = -1), but the result showed the label in the desired position but with the text off-center.

How can I fix this issue?

library(ggplot2)

Factor <- c('A', 'B')
Y <- c(5, 10)

DF <- data.frame(Factor, Y)

ggplot(data = DF,
       aes(x = Factor,
           y = Y)) +
  geom_col() +
  geom_label(aes(label = Y),
             vjust = -1,
             size = 3) +
  scale_y_continuous(limits = c(0, 15))

enter image description here

1 Answers

Instead of shifting the labels via vjust (or hjust) I would suggest to make use of nudge_y.

library(ggplot2)

Factor <- c('A', 'B')
Y <- c(5, 10)

DF <- data.frame(Factor, Y)

p <- ggplot(data = DF,
       aes(x = Factor,
           y = Y)) +
  geom_col() +
  scale_y_continuous(limits = c(0, 15))

p + geom_label(aes(label = Y), nudge_y = 1, size = 3)

A second option would be to make use of ggtext::geom_richtext which allows to add some margin between the data point and the label:

p + ggtext::geom_richtext(aes(label = Y), vjust = 0, size = 3, label.margin = unit(5, "pt"))

Related