删除ggplot中的填充图例 [英] Remove fill around legend key in ggplot

查看:146
本文介绍了删除ggplot中的填充图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除图例周围的灰色矩形。

  ggtheme<  -  
主题(
轴。 text.x = element_text(color ='black'),
axis.text.y = element_text(color ='black'),
panel.background = element_blank(),
面板。 grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_rect(color ='black',fill = NA),
strip.background = element_blank(),
legend.justification = c(0,1),
legend.position = c(0,1),
legend.background = element_rect(color = NA),
legend.key = element_rect(color =white,fill = NA),
legend.title = element_blank()


颜色< - c (红,蓝)
df < - data.frame(year = c(1:10),value = c(10:19),gender = rep(c(male,女性),每个= 5))
ggplot(df,aes(x = year,y = value))+ geom_point(aes(color = gender))+
stat_smooth(method =loess ,公式= y〜x,等级= 0,大小= 1,
aes(group = gender,color = gender))+
ggtheme + scale_color_manual(values = colors)

解决方案

由于使用 stat_smooth() code>,作为默认值,也会使用一些填充(灰色如果 fill = 不在 aes( )



一个解决方案是为<$ c设置 se = FALSE 如果你不需要置信区间,$ c> stat_smooth()

方法=黄土,公式= y〜x,等级= 0,大小= 1,
aes(group = gender,color = gender),se = FALSE)

另一个解决方案是使用函数 guides()覆盖。 aes = 从图例中删除填充,但k

  + guides(color = guide_legend(override.aes = list(fill = NA)))


I would like to remove the gray rectangle around the legend. I have tried various methods but none have worked.

ggtheme <- 
theme(
axis.text.x = element_text(colour='black'),
axis.text.y = element_text(colour='black'),
panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_rect(colour='black', fill=NA),
strip.background = element_blank(),
legend.justification = c(0, 1),
legend.position = c(0, 1),
legend.background = element_rect(colour = NA),
legend.key = element_rect(colour = "white", fill = NA),
legend.title = element_blank()
)

colors <- c("red", "blue")
df <- data.frame(year = c(1:10), value = c(10:19), gender = rep(c("male","female"),each=5))
ggplot(df, aes(x = year, y = value)) + geom_point(aes(colour=gender))  +
stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
    aes(group = gender, colour=gender)) +
ggtheme + scale_color_manual(values = colors) 

解决方案

You get this grey color inside legend keys because you use stat_smooth() that as default makes also confidence interval around the line with some fill (grey if fill= isn't used inside the aes()).

One solution is to set se=FALSE for stat_smooth() if you don't need the confidence intervals.

  +stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
              aes(group = gender, colour=gender),se=FALSE) 

Another solution is to use the function guides() and override.aes= to remove fill from the legend but keep confidence intervals around lines.

  + guides(color=guide_legend(override.aes=list(fill=NA)))

这篇关于删除ggplot中的填充图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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