ggplot2:更改 geom_vline 图例的背景颜色

时间:2021-01-26 21:35:30

标签: r ggplot2

我正在尝试遵循此 post 中建议的代码,但无济于事。

具体来说,我希望与红色垂直线相关的图例具有白色背景

一些玩具数据:

df1 <- data.frame(correlation = c(rnorm(1000, 0, 0.6), rnorm(1000, 0, 0.1)), type = c(rep("Real", 1000), rep("Permuted", 1000)))

corSig <- 0.24542

我的代码:

ggplot(df1, aes(correlation, fill = type)) +
    geom_density(alpha = .5) +
    geom_vline(aes(xintercept = signif(corSig, 2), linetype = 'FDR = .05'), colour = 'red') +
    theme(plot.title = element_text(hjust = .5),
          plot.subtitle = element_text(hjust = .5),
          legend.title = element_blank(),
          legend.position = c(.8, .8),
          panel.background = element_blank()) +
    guides(linetype = guide_legend(override.aes = list(fill = "#000000"))) +
    ggtitle("Gene Expression Correlation", subtitle = paste(nrow(datExpr), "genes,", ncol(datExpr), "bulk sections")) +
    xlab("Correlation") +
    ylab("Density")

enter image description here

1 个答案:

答案 0 :(得分:2)

这个问题似乎没有一致的解决方案(至少对我来说),但我在这里有一个解决方案:

library(tidyverse)

df1 <- data.frame(correlation = c(rnorm(1000, 0, 0.6), rnorm(1000, 0, 0.1)), type = c(rep("Real", 1000), rep("Permuted", 1000)))

corSig <- 0.24542

ggplot(df1, aes(correlation, fill = type)) +
    geom_density(alpha = .5) +
    geom_vline(aes(xintercept = signif(corSig, 2), linetype = 'FDR = .05'), colour = 'red') +
    theme(
        plot.title = element_text(hjust = .5),
        plot.subtitle = element_text(hjust = .5),
        legend.title = element_blank(),
        legend.position = c(.8, .8),
        panel.background = element_blank(),
        legend.key = element_rect(colour = "transparent", fill = "transparent")) +
    ggtitle("Gene Expression Correlation", subtitle = paste(nrow(df1), "genes,", ncol(df1), "bulk sections")) +
    xlab("Correlation") +
    ylab("Density")

Fixed Gene Expression Correlation Plot

简而言之,我删除了 ...guides(linetype = guide_legend(override.aes = list(fill = "#000000")))... 并添加了 ...legend.key = element_rect(colour = "transparent", fill = "transparent"))...

希望有帮助!