使用ggcorrplot2的R相关图:“ x轴”标签被裁剪

问题描述

我正在使用ggcorrplot2github page)来生成我的相关图,因为我需要在顶部像***那样覆盖显着性水平。

此软件包依赖ggplot2,因此我认为更改轴标签字体大小,星号颜色,渐变颜色等不同功能将很容易。但是事实证明,它比我想的要复杂。

我当前遇到的问题是“ x轴”标签被裁剪到绘图区域之外...正如您在下面看到的,这实际上不是x-axis,而是标签放在顶部对角细胞。因此,很难更改它们。

查看此MWE。我首先这样做:

data(mtcars)
#change "wt" to a very long name
names(mtcars)[6] <- "a very long name"

corrtest <- psych::corr.test(mtcars[,1:7],adjust="none")
all_matrix <- corrtest$r
all_pmat <- corrtest$p

###

P <- ggcorrplot2::ggcorrplot(all_matrix,type = "lower",method = "circle",p.mat = all_pmat,show.diag = FALSE,insig = "label_sig",sig.lvl = c(0.05,0.01,0.001),pch = "*",pch.cex = 6) +
     ggplot2::theme(axis.text.y=ggplot2::element_text(size=15),legend.text=ggplot2::element_text(size=15))
Grdevices::pdf(file="heat_all2.pdf",height=6,width=6)
print(
  P
)
Grdevices::dev.off()

哪个产生这个:

test1

如您所见,我能够使用y-axis主题修改ggplot2标签,但不能修改“ x轴”标签或其他任何东西...

所以我认为我可以使用ggplot_build并在实际打印之前对图进行调整,然后执行以下操作:

P <- ggcorrplot2::ggcorrplot(all_matrix,legend.text=ggplot2::element_text(size=15))
P2 <- ggplot2::ggplot_build(P)
P2$data[[4]]$size <- 5
P2$data[[4]]$hjust <- 0
P2$data[[3]]$angle <- 15
P2$data[[3]]$colour <- "grey30"
Grdevices::pdf.options(reset = TRUE,onefile = FALSE)
Grdevices::pdf(file="heat_all2.pdf",width=6)
print(
  graphics::plot(ggplot2::ggplot_gtable(P2))
)
Grdevices::dev.off()

哪个产生这个:

test2

非常接近,但还不很远。我一直遇到的问题如下:

  • “ x轴”标签被裁剪
  • 情节顶部和底部的怪异灰色区域
  • 我想更改颜色渐变,所以深蓝色和深红色 不是黑暗

我试图通过在plot.margin=grid::unit(c(0,3,0),"cm")添加theme解决此问题,但结果是这样的(标签仍然被裁剪,图的顶部和底部还有更多的灰色空间):

test3

有帮助吗?谢谢!

解决方法

original function中,作者在expand = c(0,0)中设置了scale_x_continuous()。您只需要修改该部分即可获得所需的内容

library(tidyverse)
library(ggcorrplot2)

data(mtcars)
# change "wt" to a very long name
names(mtcars)[6] <- "a very long name"

corrtest <- psych::corr.test(mtcars[,1:7],adjust = "none")
all_matrix <- corrtest$r
all_pmat <- corrtest$p

###
P <- ggcorrplot2::ggcorrplot(all_matrix,type = "lower",method = "circle",p.mat = all_pmat,show.diag = FALSE,insig = "label_sig",sig.lvl = c(0.05,0.01,0.001),pch = "*",pch.cex = 6) +
  ggplot2::theme(axis.text.y = ggplot2::element_text(size = 15),legend.text = ggplot2::element_text(size = 15))

P +
  scale_x_continuous(expand = expansion(mult = c(0,0.25)))
#> Scale for 'x' is already present. Adding another scale for 'x',which will
#> replace the existing scale.

reprex package(v0.3.0)于2020-09-01创建