Search code examples
rggplot2positionaxis-labels

Altering axes positions in ggplot scales lets hjust/vjust of theme(axis.text) to be ignored


I want to create a plot with the x-axis at the top and the axis labels rotated 90 degrees center-aligned with the ticks. This is my code:

library(tidyverse)

# create data
a3 <- rnorm(100, 0, 1)
aaa4 <- rnorm(100, 0, 1)
aaaa5 <- rnorm(100, 0, 1)

df_2 <- data.frame(a3, aaa4, aaaa5)

correlation_matrix_2 <- cor(df_2)

corr_long <- correlation_matrix_2 %>% 
  as.data.frame(.) %>% 
  rownames_to_column(., var = "V1") %>% 
  pivot_longer(., cols = -V1, names_to = "V2", values_to = "r")

# plot:
ggplot(corr_long, aes(V1, V2))+
  geom_tile(mapping = aes(fill = r))+
  scale_x_discrete(position = "top")+
  theme(axis.text.x = element_text(size = 16, angle = 90, hjust = 0, vjust = .5))

However, the plot ignores the vjust parameter of the theme and always positions the labels a little bit off. This only happens when the axis is set to be at the top using position parameter from scale_x_discrete, it works fine for "bottom". The hjust works as expected in both cases.

I then tried a few other things and found that it also happens when the y axis is set to the right, but then it is hjust that is ignored and vjust works. It also happens for scale_x/y_continuous. Changing the order (theme first, then scale_x_discrete) does not change anything either and also splitting it in two separate commands does not work:

[...]
theme(axis.text.x = element_text(hjust = 0))+
theme(axis.text.x = element_text(vjust = 1))+
[...]

Is that a bug or do I miss something here?


Solution

  • You can adjust the position of the axis text at the top using the axis.text.x.top argument of the theme() function instead of axis.text.x. Similarly, you can use axis.text.y.right for y-axis text on the right hand side. For example:

    ggplot(corr_long, aes(V1, V2))+
      geom_tile(mapping = aes(fill = r))+
      scale_x_discrete(position = "top")+
      theme(axis.text.x.top = element_text(size = 16, angle = 90, hjust = 0, vjust = .5))