2017-08-05 146 views
2

我用这data.frame,这下面我有dput,三个坡映射使用geom_ablineGGPLOT2:图例标识多个geom_abline斜坡

moderator_value simple_intercept simple_slope 
1    -1  -0.02745523 0.2768973 
2    0  0.05990693 0.2147829 
3    1  0.14726909 0.1526684 

我现在所拥有的是这样的代码:

ggplot() + 
    geom_abline(data=ablines, 
       mapping=aes(slope=simple_slope, intercept=simple_intercept), 
       linetype=c(1,2,3)) + 
    scale_x_continuous(limits=c(-1.5,2), name="Prejudice") + 
    scale_y_continuous(limits=c(-.75, .75), name="Authenticity") + 
    theme_light() + 
    theme(text=element_text(size=14)) 

这将返回数字:

enter image description here

我想添加一个图例,它们的linetype标记这三个单独的行。我在其他地方看过,但其中很多人说show_guidegeom_abline函数中(现在已经弃用show.legend),并将其设置为TRUE。这不适合我。我也尝试过使用scale_linetype_manual,但没有运气。

如何包含一个分别标记每条线的图例?我想包含主持人变量的名称以及“-1 SD”,“Mean”和“+1 SD”作为标签。

ablines数据dput

structure(list(moderator_value = c(-1, 0, 1), simple_intercept = c(-0.0274552251655293, 
0.0599069333124192, 0.147269091790368), simple_slope = c(0.276897278474258, 
0.214782863579552, 0.152668448684846)), .Names = c("moderator_value", 
"simple_intercept", "simple_slope"), row.names = c(NA, 3L), class = "data.frame") 

回答

2

你应该尝试做的是地图中的每个线的独特功能(即主持人的一个因素(BC我们不希望把它解释为连续变量))到线型。

例如通过使用此代码

ablines <- structure(list(moderator_value = c(-1, 0, 1), 
          simple_intercept = c(-0.0274552251655293, 0.0599069333124192, 0.147269091790368), 
          simple_slope = c(0.276897278474258, 0.214782863579552, 0.152668448684846)), 
        .Names = c("moderator_value", "simple_intercept", "simple_slope"), 
        row.names = c(NA, 3L), class = "data.frame") 

library(ggplot2) 
ggplot(ablines) + 
geom_abline(mapping = aes(slope = simple_slope, 
          intercept = simple_intercept, 
          linetype = as.factor(moderator_value))) + 
scale_x_continuous(limits=c(-1.5,2), name="Prejudice") + 
scale_y_continuous(limits=c(-.75, .75), name="Authenticity") 

2

为了让你不得不爱依斯内的lynetipe一个变量映射()的传说。在你的代码中,你在aes()之外指定了它。 请注意,在我的代码中,变量“moderator”的数值将该数字映射到ggplot的可用线条样式。 要为每个线型提供自定义名称,请取消注释最后的指令。

ggplot() + 
     geom_abline(data=ablines, 
        mapping=aes(slope=simple_slope, intercept=simple_intercept, linetype = moderator_value)) + 
     scale_x_continuous(limits=c(-1.5,2), name="Prejudice") + 
     scale_y_continuous(limits=c(-.75, .75), name="Authenticity") + 
     theme_light() ## + 
     ## scale_linetype_continuous(labels = c("First Line", "Second Line", "Third Line")