绘图区域顶部的X轴标签

时间:2016-01-09 01:36:05

标签: r plot ggplot2 fonts heatmap

我正在使用switch_axis_position在顶部绘制x轴相关热图。 x轴标签有点长,所以我希望使用angle=90旋转它并使用hjust=0对齐它们。 但这会使标签离x轴太远甚至使它们离开绘图区域。

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'))

enter image description here 我怎么能这么漂亮?任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:4)

幸运的是,我喜欢编造数据。

所以这可能是你想要的。我做了以下事情:

  • hjust以接近看起来没问题
  • 用空格填充名称以使它们具有相同的长度
  • 将字体系列更改为"mono",因此轴文本将对齐

库(gtable) 库(cowplot) 库(网格)

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'))

它产生了这个:

enter image description here