Search code examples
rggplot2cowplot

Left-aligned axis labels when using cowplot to switch x axis to top


I'm trying to make a correlation heatmap where the x axis is moved to the top using cowplot::switch_axis_position. I have axis labels of varying length and I want the labels to be left-aligned (or rather bottom-aligned, because they are rotated 90 degrees). Although I manage to align the labels, they are moved up far above the plot.

library(reshape2)
library(ggplot2)
library(cowplot)

# some toy data
set.seed(1)
mydata <- mtcars[, c(1, 3, 4, 5, 6, 7)]

# to show difference in justification better, make names of unequal length 
names(mydata) = paste0(sample(c("mtcars_", ""), 6, replace = TRUE), names(mydata))
cormat <- round(cor(mydata), 2)

melted_cormat <- melt(cormat)
head(melted_cormat)

First a plot where the x axis is moved to the top, and the labels are centered vertically:

plot <- ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + 
        geom_tile() +
        theme_bw(base_size=20) + xlab("") + ylab("") +
        theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 0.5))
ggdraw(switch_axis_position(plot, 'x'))

link

Then I use the same code as above but with hjust = 0 instead to left-align the x axis text. It indeed aligns the text, but the text is moved weirdly far from graph so variable names are cut off: link

Any ideas of how to fix this?


Solution

  • Please note: this bug is no longer present in the latest version of cowplot on CRAN.

    Old answer:

    It seems this is a bug for the special case of angle = 90. We can circumvent this by adding an arbitrarily small value to angle.

    plot <- ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + 
      geom_tile() + theme_bw(base_size=20) + xlab("") + ylab("")+
      theme(axis.text.x=element_text(angle=90 + 1e-09, hjust = 0, vjust=1)) +
      coord_equal(expand = 0)
    ggdraw(switch_axis_position(plot, 'x'))
    

    enter image description here