Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

cowplot

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?

like image 532
Esther Avatar asked Feb 17 '16 17:02

Esther


People also ask

How do you rotate the X axis labels?

Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax. set_xticklabels() and ax.

How do you align a plot in Cowplot?

If we want to align and then arrange plots, we can call plot_grid() and provide it with an align argument. The plot_grid() function calls align_plots() to align the plots and then arranges them.


1 Answers

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

like image 69
Axeman Avatar answered Sep 21 '22 20:09

Axeman