【问题标题】:How to show abline of geom_abline in legend如何在图例中显示 geom_abline 的 abline
【发布时间】:2014-07-17 20:10:32
【问题描述】:

在以下示例数据中,我如何在图例中用 y 显示 abline(即红色线)。 我的代码和数据:

x<-c(1990,1991,1992,1993,1994,1995)
y<-c(400,500,465,450,550,555)

df<-data.frame(x,y)
df
plot1<- ggplot(df, aes(x)) +
        geom_line(size=0.5,lty="dashed", aes(y=y),color="Blue") +
        geom_abline(aes(slope=-0.62,intercept=1670,colour="break"),size=0.9)+
        geom_point(aes(y=y,shape="y"),size=4, color="Gray24",fill="Green")
plot1

。 我得到的是下面的 图像。我需要在图例中显示红线

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以使用show_guide=TRUE 参数:

    plot1<- ggplot(df, aes(x)) +
      geom_line(size=0.5,lty="dashed", aes(y=y),color="Blue") +
      geom_abline(aes(slope=-0.62,intercept=1670,colour="break"), size=0.9,show_guide = TRUE)+
      geom_point(aes(y=y,shape="y"),size=4, color="Gray24",fill="Green")
    

    您可能需要更改图例中的标签,但您应该可以使用 theme 来做到这一点。

    编辑:要从图例中删除斜线,您可以使用guidesoverride.aes

    plot1 <- ggplot(df, aes(x, y)) +
      geom_point(aes(shape = "y"), size = 4, color = "Gray24", lty = 0) +
      geom_line(size = 0.5, lty = "dashed", color = "Blue") +
      geom_abline(aes(slope = -0.62, intercept = 1670, colour = "break"), size = 0.9, 
                   show_guide = TRUE) +
      guides(shape = guide_legend(override.aes = list(linetype = 0)))
    

    【讨论】:

    • 谢谢 tkmckenzie,但那不给我想要的。它用线重叠点。您可以运行并查看线和点的重叠。所以这不是我所期望的。你知道如何消除这种重叠吗?
    • @Cirrus 解决这个问题有点棘手,涉及使用 guidesoverride.aes,但我已经在上面的编辑中发布了它,希望这会给你你的寻找。
    • 这可能发生:show_guide 已被弃用。请改用show.legend。另一方面,就我而言,我没有运气使用show.legend,而show_guide 产生了错误消息,但仍然给了我传说......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多