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'))
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:
Any ideas of how to fix this?
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.
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.
cowplot
on CRAN.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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With