In R ggplot2 , 'vjust' and 'nudge_y' can adjust text position for the vertical axis. Can anyone tell me the difference of the two parameters?
library(tidyverse)
plot_data <- data.frame(cagegory=LETTERS[1:5],amount=c(1:5))
plot_data %>% ggplot(aes(x=cagegory,y=amount))+geom_bar(stat='identity')+
geom_text(size=10,vjust=1,color='white',aes(label=cagegory))+
geom_text(size=10,nudge_y=1,color='red',aes(label=cagegory))+
theme_minimal()
The vjust
parameter specifies justification orthogonal to the direction of the text in terms of stringheight. It is commonly misconceived as 'vertical' justication, but this is only true when the angle of the text is 0. Notice that in your example, the white text starts exactly 1 stringheight under the bar's top. If you set vjust = 2
, it will start 2 stringheights under the bar's top.
It's perhaps easier to see it in terms of stringheight when you have a multi-line label:
library(tidyverse)
#> Warning: package 'readr' was built under R version 4.1.1
plot_data <- data.frame(category=LETTERS[1:5],amount=c(1:5))
p <- ggplot(plot_data, aes(x = category, y = amount)) +
geom_col() +
theme_minimal()
p + geom_text(size = 10 , vjust = 1, colour = "white",
aes(label = paste0(category, "\n", category)))
The nudge_y
parameter gives you how many y-axis units to shift the text. Notice that the red text in your example is centred at 1 unit above the bar (the centring is because the default vjust = 0.5
).
p + geom_text(size = 10, nudge_y = 1, color = "red",
aes(label = category))
Created on 2021-09-07 by the reprex package (v2.0.1)
Likewise the hjust
parameters specifies justification in the direction of the text in terms of stringwidth, and nudge_x
is a shift along the x-axis.