Reputation: 83
I'm plotting a correlation heatmap with x-axis on top by using switch_axis_position
.
The x-axis labels are somewhat long, so I want it to be rotated by using angle=90
and align them by using hjust=0
.
But this makes the labels too far from the x-axis and even gets them out of the plot area.
library(gtable)
library(cowplot)
library(grid)
heatmap<-ggplot(data=meltedh, aes(x=variable, y=X, fill=value))+
geom_tile(color="White")+
ylab("")+xlab("")+
scale_fill_gradient2(low="blue3", high="red3", mid="white",
midpoint=0,limit=c(-1,1), space="Lab", breaks=c(-0.5,0,0.5),
name="Correlation Coefficient")+
theme(legend.position="bottom",
axis.text.x=element_text(angle=90, hjust=0))
heatmap
ggdraw(switch_axis_position(heatmap,axis='x'))
How can I make this pretty? Any help would be great. Thanks.
Upvotes: 2
Views: 4081
Reputation: 22807
Lucky for you I rather enjoy making up data.
So this might be what you want. I did the following things:
hjust
to get it close to looking okay "mono"
, so the axis text would be alignedlibrary(gtable) library(cowplot) library(grid)
set.seed(1234)
cn <- c("Eastside","Pygrate","Tapeworm","Annerose","Bund",
"Mountain","Appalacia","Summer","Treasure","Riveria",
"Persia","Raggout","Bengal","Siam","Norman")
# Pad out the names with spaces to all be the same length
mxl <- max(nchar(cn))
fmt <- sprintf("%%-%ds",mxl) # the minus adds spaces to the string end
cn <- sprintf(fmt,cn)
rn <- rev(letters[1:16])
ddf <- expand.grid( x=rn, y=cn )
n <- nrow(ddf)
ddf$v <- runif(n,-1,-0.1)
nr <- n/length(cn)
ddf[ddf$y==cn[3],]$v <- runif(nr,0.1,0.8)
ddf[ddf$y==cn[8],]$v <- runif(nr,0.1,0.8)
ddf[ddf$y==cn[13],]$v <- runif(nr,0.1,0.8)
ddf[ddf$x %in% c("i","j","n","o"),]$v <- 0
meltedh <- data.frame(X=ddf$x,variable=ddf$y,value=ddf$v)
heatmap<-ggplot(data=meltedh, aes(x=variable, y=X, fill=value))+
geom_tile(color="White")+
ylab("")+xlab("")+
scale_fill_gradient2(low="blue3", high="red3", mid="white",
midpoint=0,limit=c(-1,1), space="Lab", breaks=c(-0.5,0,0.5),
name="Correlation Coefficient")+
theme(legend.position="bottom",
axis.text.x=element_text(angle=90, hjust=0.5,family="mono"))
heatmap
ggdraw(switch_axis_position(heatmap,axis='x'))
It yields this:
Upvotes: 4