Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

r - ggplot2: Change color of background for geom_vline legend

I'm trying to follow the code suggested in this post, but to no avail.

Specifically, I would like the legend associated with the red vertical line to have a white background.

Some toy data:

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

My code:

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

question from:https://stackoverflow.com/questions/65909610/ggplot2-change-color-of-background-for-geom-vline-legend

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There doesn't seem to be a consistent solution for this issue (for me, at least) but I've got a solution here:

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

In short, I removed ...guides(linetype = guide_legend(override.aes = list(fill = "#000000")))... and added ...legend.key = element_rect(colour = "transparent", fill = "transparent"))...

Hopefully that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...