小tips: 如何画简单的correlation图并调整图距

记录简单的画correlation代码。初衷是每次都需要找这个边距到底是哪个代码,特此记录。

目的:我们有一组需要添加的r和pvalue,然后我们想把它加到图里然后并且调整图的边距。

测试数据构建以及r和p给定以及对其进行四舍五入规定小数点以及科学计数法的转换。

library(tidyverse)

library(ggpubr)

r <- c(0.4321 %>% round(., digits = 3), 0.6543 %>% round(., digits = 3))

p_values <- c(0.987654e-34, 0.287654e-54)

p_values <- scales::scientific(p_values, digits = 3)

index <- c("col1", "col2")

fake_table <- tibble(col1 = runif(100, 0.34,0.88), col2 = runif(100, 0.77, 0.94), percentage = runif(100, 0.24, 0.77))


画图

p <- list()
for (x in c("col1", "col2")){

        r_target <- r[which(index == x)]
        p_target <- p_values[which(index == x)]
        label <- paste0("Correlation, ","r", " = ", r_target, ", ", "p = ", p_target)
        label <- paste0("R", " = ", r_target, ", ", "p = ", p_target)

        p[[x]] <- ggscatter(fake_table, x = x, y = "percentage",
          add = "reg.line", conf.int = TRUE, add.params = list(color = "red"),
          cor.coef = FALSE, cor.method = "spearman", cor.coef.size = 8,
          xlab = x, ylab = "my y lab") +
          annotate("text", x = 0.55*max(fake_table[,x]), y = 0.98*max(fake_table[,"percentage"]),
                       label = label,
                       color = "black", size = 6) +
          theme(text = element_text(size=30),
                axis.line = element_line(colour = "black"),
                #panel.grid.major = element_blank(),
                panel.grid.minor = element_blank(),
                panel.border = element_blank(),
                panel.background = element_blank(),
                axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)),
                plot.margin = margin(1,1,1.5,1.2, "cm"))
}

样图 

其中annotate是想要加的r和p的位置坐标,这里是以0.55的max(x)还有0.98的max(y)加的,可以随意调整。然后grid和border都设为没有。

axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)) 这里调整的是x 坐标的title和x轴的距离 

plot.margin = margin(1,1,1.5,1.2, "cm")这里调整的是图和画布的边缘距离。

p[["col1"]] 示例

小tips: 如何画简单的correlation图并调整图距_第1张图片

你可能感兴趣的:(小tips,生物信息)