图例中 geom_hline 的颜色不正确 [ggplot2]

Posted

技术标签:

【中文标题】图例中 geom_hline 的颜色不正确 [ggplot2]【英文标题】:Colour of geom_hline is not correct in legend [ggplot2] 【发布时间】:2014-05-18 17:53:34 【问题描述】:

我在 SO 上环顾四周,但似乎找不到解决方案。我在 ggplot2 中使用了 geom_point 和 geom_hline 并且得到了令人满意的图例。但是,我在图中有一条黑线和一条蓝线,但在图例中它们都是黑色的 - 我如何在图例中将其纠正为正确的颜色?

mcgc <- ggplot(sam, aes(x = Person,y = mm, colour = X)) +
                  geom_point(size = 0.75) +
                  scale_colour_gradient2(high="red", mid="green", limits=c(0,1), guide = "colourbar") +
                  geom_hline(aes(yintercept = mad, linetype = "mad"), colour = "blue", size=0.75, show_guide = TRUE) +
                  geom_hline(aes(yintercept = mmad, linetype = "mmad"), colour = "black", size=0.75, show_guide = TRUE)  +
                  facet_wrap(~ Plan, scales = "free", ncol = 4) +
                  scale_linetype_manual(name = "Plan of Health Care", values = c("mad" = 1, "mmad" = 1),guide = "legend")

我确定我在这里写了一些东西......只是不确定在哪里(我是 ggplot 新手)

数据:

Plan  Person X       mm  mad mmad
1  1 95 0.323000 0.400303 0.12
1  2 275 0.341818 0.400303 0.12
1  3  2 0.618000 0.400303 0.12
1  4 75 0.320000 0.400303 0.12
1  5 13 0.399000 0.400303 0.12
1  6 20 0.400000 0.400303 0.12
2  1 219 0.393000 0.353350 0.45
2  2 50 0.060000 0.353350 0.45
2  3 213 0.390000 0.353350 0.45
2  4 204 0.496100 0.353350 0.45
2  5 19 0.393000 0.353350 0.45
2  6 201 0.388000 0.353350 0.45

计划增加到 40,但我在这里只包含了一个 sn-p 数据...

更新:对于那些可能会有所帮助的人 - 我绘制数据的代码是错误的。我已经更新了。

【问题讨论】:

如果您通过编辑问题以包含您的数据(例如,sam,以及madmmad 的值)将此作为可重复的示例,您更有可能获得帮助. 更新了我的问题以包含数据。 【参考方案1】:

由于您已经使用颜色作为点,因此您不能使用scale_color_.. 作为线在图例中显示颜色。解决方法是使用函数guides() 和参数override.aes= 为图例添加颜色。将此行添加到您现有的代码中。

  + guides(linetype=guide_legend(override.aes=list(colour = c("blue","black"))))

【讨论】:

太棒了 - 我知道是这段代码,但一直在错误的地方得到 linelinetypecolour。你是明星!

以上是关于图例中 geom_hline 的颜色不正确 [ggplot2]的主要内容,如果未能解决你的问题,请参考以下文章

根据组在图例中添加平均线 - geom_hline

如何为 geom_hline 添加自定义图例

在 geom_line 图中显示多个分组 geom_hline 的图例

在使用 gghighlight 时为几个 geom_hlines 创建图例

如何在同一个散点图上使用 geom_vline() 和 geom_hline 避免图例中的交叉效应?

ggplot:geom_vline 和 geom_hline 的单独图例