使用平滑时无法删除图例符号后面的灰色区域 [英] Cannot remove grey area behind legend symbol when using smooth

查看:94
本文介绍了使用平滑时无法删除图例符号后面的灰色区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有GAM平滑功能的ggplot2来查看两个变量之间的关系.绘制时,我想删除两种类型变量的符号后的灰色区域.为此,我将使用theme(legend.key = element_blank()),但是使用平滑器时似乎不起作用.

I'm using ggplot2 with a GAM smooth to look at the relationship between two variables. When plotting I'd like to remove the grey area behind the symbol for the two types of variables. For that I would use theme(legend.key = element_blank()), but that doesn't seem to work when using a smooth.

谁能告诉我如何删除图例中两条黑线后面的灰色区域?

Can anyone tell me how to remove the grey area behind the two black lines in the legend?

我下面有一个MWE.

library(ggplot2)

len <- 10000
x <- seq(0, len-1)
df <- as.data.frame(x)
df$y <- 1 - df$x*(1/len)
df$y <- df$y + rnorm(len,sd=0.1)
df$type <- 'method 1'
df$type[df$y>0.5] <- 'method 2'

p <- ggplot(df, aes(x=x, y=y)) + stat_smooth(aes(lty=type), col="black", method = "auto", size=1, se=TRUE)
p <- p + theme_classic()
p <- p + theme(legend.title=element_blank())
p <- p + theme(legend.key = element_blank()) # <--- this doesn't work?
p

推荐答案

这是一个非常棘手的解决方法,其基于以下概念:如果您将事物映射到ggplot中的美学,则它们会出现在图例中. geom_smooth具有填充美感,如果需要,可以允许不同组使用不同的颜色.如果很难在下游修复该问题,则有时将那些不需要的项目完全排除在图例之外会更容易.在您的情况下,se的颜色出现在图例中.这样,我创建了两个geom_smooths.一个没有线条颜色(但按类型分组)来创建绘制的se的线,一个将线型映射到aes但se设置为false的线.

Here is a very hacky workaround, based on the notion that if you map things to aestethics in ggplot, they appear in the legend. geom_smooth has a fill aesthetic which allows for different colourings of different groups if one so desires. If it's hard to fix that downstream, sometimes it's easier to keep those unwanted items out of the legend altogether. In your case, the color of the se appeared in the legend. As such, I've created two geom_smooths. One without a line color (but grouped by type) to create the plotted se's, and one with linetype mapped to aes but se set to false.

p <- ggplot(df, aes(x=x, y=y)) + 
  #first smooth; se only
  stat_smooth(aes(group=type),col=NA, method = "auto", size=1, se=TRUE)+
  #second smooth: line only
  stat_smooth(aes(lty=type),col="black", method = "auto", size=1, se=F) +
  theme_classic() +
  theme(
    legend.title = element_blank(),
    legend.key = element_rect(fill = NA, color = NA)) #thank you @alko989

这篇关于使用平滑时无法删除图例符号后面的灰色区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆