ggplot2绘图如何隐藏图例中geom_jitter元素 仅保留线段标签
问题原因
你当前的代码中geom_jitter和geom_segment都将变量映射到了color美学,ggplot2默认会把所有映射到同一个美学的分类值合并到同一个图例中,即使你给geom_jitter设置了show.legend = F,部分版本下仍可能出现散点的分类项混入图例的情况。
解决方案
这里提供两种常用实现方式:
方案1:通过scale_color的breaks参数过滤不需要的图例项
直接在颜色标度中指定仅保留线段对应的dashed和solid两个分类即可:
Author_csv %>% ggplot(aes(x=X, y=Y)) + geom_jitter(aes(color=Autor), show.legend = F) + geom_segment(aes(x = 0, xend = 7, y = 0, yend = 3.5, colour = "dashed"), linetype="dashed", size=0.3) + geom_segment(aes(x = 0, xend = 7, y = 7, yend = 3.5, colour = "dashed"), linetype="dashed", size=0.3) + geom_segment(aes(x = 0, xend = 7, y = 0, yend = 7, colour = "solid"), linetype="solid", size=0.3) + # 新增:仅保留线段的两个分类在图例中 scale_color_discrete(breaks = c("dashed", "solid"))
如果你的代码后续自定义了颜色,使用scale_color_manual的话同理,在scale_color_manual里加breaks = c("dashed", "solid")参数即可。
方案2:分开散点和线段的美学映射
给散点用fill映射分类,线段继续用color,两者图例完全独立,直接关闭散点的fill图例即可:
Author_csv %>% ggplot(aes(x=X, y=Y)) + # 散点改用支持fill的shape=21,边框设为透明,fill映射Autor geom_jitter(aes(fill=Autor), shape=21, color=NA, show.legend = F) + geom_segment(aes(x = 0, xend = 7, y = 0, yend = 3.5, colour = "dashed"), linetype="dashed", size=0.3) + geom_segment(aes(x = 0, xend = 7, y = 7, yend = 3.5, colour = "dashed"), linetype="dashed", size=0.3) + geom_segment(aes(x = 0, xend = 7, y = 0, yend = 7, colour = "solid"), linetype="solid", size=0.3)
这种方式适合后续需要分别自定义散点和线段颜色的场景。
你当前生成的原图参考:
内容的提问来源于stack exchange,提问作者DWA
相关产品推荐
相关产品推荐

