首页 > 解决方案 > R:GGPLOT2:如何使用 stat_summary 在 ggplot2 的折线图中添加标签

问题描述

我有下面的代码,传说都是错误的。黑线显示为紫色,在图例中颜色标签是错误的。对于红色,它说黑色等。

ggplot(newdata,aes(x=immigrants.per.day,y=cc.percent),show.legend = TRUE) +
+       stat_summary(aes(y = cc.percent, color = "red"),fun = mean, geom = "line", label = c('CC'), show.legend = TRUE) + 
+       stat_summary(aes(y = cd.percent, color = "blue"),fun = mean, geom = "line", show.legend = TRUE) + 
+       stat_summary(aes(y = dc.percent, color = "green"),fun = mean, geom = "line", show.legend = TRUE) +
+       stat_summary(aes(y = dd.percent, color = "black"),fun = mean, geom = "line", show.legend = TRUE)

在此处输入图像描述

我确实按照下面的链接但无法解决我的问题。

如何在 ggplot2 中为使用 stat_summary 制作的线条添加图例?

标签: rggplot2

解决方案


你可以做

ggplot(newdata,aes(x=immigrants.per.day,y=cc.percent),show.legend = TRUE) +
       stat_summary(aes(y = cc.percent, color = "a1"),fun = mean, geom = "line", label = c('CC'), show.legend = TRUE) + 
       stat_summary(aes(y = cd.percent, color = "a2"),fun = mean, geom = "line", show.legend = TRUE) + 
       stat_summary(aes(y = dc.percent, color = "a3"),fun = mean, geom = "line", show.legend = TRUE) +
       stat_summary(aes(y = dd.percent, color = "a4"),fun = mean, geom = "line", show.legend = TRUE)+
scale_colour_manual("", 
                      breaks = c("a1", "a2", "a3","a4"),
                      values = c("red", "blue", "green","black"))

推荐阅读