LC-datascientist
LC-datascientist

Reputation: 2096

How do I center text in geom_label box in R ggplot?

When using geom_label for my (gg)plots in R, I notice that there is too much space above the text than there is below. How do I align the text to be in middle of the label box?

x <- data.frame(x = c("Being not", "Creative"), y = c(0.5, 1), text = c(543,12345))

g <- ggplot(data=x, aes(x, y)) + geom_bar(stat = 'identity', fill=c("red4","cornflowerblue"))

g + geom_label(aes(y = -Inf, label = text), vjust = -2)

# increasing `label.padding` here to exaggerate the white space
g + geom_label(aes(y = -Inf, label = text), vjust = -2, label.padding = unit(1, "lines")

Illustrative Sample

Upvotes: 4

Views: 7768

Answers (1)

Rich Pauloo
Rich Pauloo

Reputation: 8392

Use explicit y coordinates to place the label instead of vnudge


g + geom_label(aes(y = .25, label = text), label.padding = unit(1, "lines"))

enter image description here

Better yet: pass a vector of y coordinates to the y aes to specify midpoints.

g + geom_label(aes(y = c(.25, .5) label = text), label.padding = unit(1, "lines"))

enter image description here

Upvotes: 5

Related Questions