从颜色中删除线条并填充图例

drm*_*iod 17 r ggplot2

我有一个有三个不同传说的情节:一个用于linetype,一个用于color,一个用于fill.在colorfill传说中还有一些我希望删除的行,但是如何?

这是一些示例代码:

# some data
hline_df <- data.frame(name = c('a', 'b'), y = c(1, 2))
df <- data.frame(x = c(1, 2), y = c(0.5, 1.5), con = c('a', 'b'), col = c('d', 'e'))

# the plot
ggplot(df, aes(x, y, fill = con)) +
  geom_bar(stat = 'identity') + 
  geom_point(aes(color = col)) +
  geom_hline(data = hline_df, aes(yintercept = y, linetype = name),
             color = 'red', show_guide = TRUE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我得到两条红线的"名称"指南,很好.
"col"指南有红线穿过点,我想删除它们!
"con"指南也有红线,应删除.

我可以修改图例的部分内容

guides(fill = guide_legend(override.aes = list(colour = NULL)),
       color = guide_legend(override.aes = list(colour = NULL)))
Run Code Online (Sandbox Code Playgroud)

这会删除颜色,但线条仍然存在.

提前致谢!

Hen*_*rik 20

你可以设置linetype = 0"blank"(在不同的linetype小号在这里)的fill,并color guide在你的S override.aes通话.

另请注意,我将fill aes"顶级" ggplot移至geom_bar.

ggplot(df, aes(x, y)) +
  geom_bar(aes(fill = con), stat = 'identity') + 
  geom_point(aes(color = col)) +
  geom_hline(data = hline_df, aes(yintercept = y, linetype = name), color = 'red', show_guide = TRUE) +
  guides(fill = guide_legend(override.aes = list(linetype = 0)),
         color = guide_legend(override.aes = list(linetype = 0)))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


drm*_*iod 5

根据用户20650的建议

ggplot(df, aes(x,y)) + 
  geom_hline(data=hline_df,aes(yintercept=y,linetype=name), color='red',show_guide=TRUE) + 
  geom_point(aes(color=col), size=5) + 
  geom_bar(aes(fill=con), stat='identity') + 
  geom_hline(data=hline_df,aes(yintercept=y,linetype=name), color='red',show_guide=F) + 
  guides(color = guide_legend(override.aes = list(linetype = 0)))
Run Code Online (Sandbox Code Playgroud)

因此,第一个 geom_hline 创建图例,但线条位于条形后面...
第二个调用将线条置于条形前面,但不打印图例(好主意)。
las 指南用 0 覆盖美学线型...通过这种方式,它从图例中删除了该线...我尝试过,NULL但这之前不起作用...

再次感谢。

在此输入图像描述