首页 文章

在geom_smooth,ggplot2中设置不同的线型

提问于
浏览
2

我正在尝试为数据设置一个多元回归模型的图,如下所示:

subject iq      condition RT
1       98      A         312
1       98      B         354
1       98      C         432
2       102     A         134
2       102     B         542
2       102     C         621
...     ...     ...       ...

等等 .

我想在x轴上绘制iq,在y轴上绘制RT,并使用具有不同线型的不同颜色的线(虚线,点线,例如)用于不同的条件 .

到目前为止,我的代码看起来像这样:

ggplot(DFplotlong, aes(iq, RT, colour = condition)) 
+ geom_smooth(method = lm, fullrange = TRUE, alpha = .15) 
+ theme_bw() 
+ labs(x = "iq", y = "reaction times") 
+ scale_colour_manual(values=c("#999999","#000000"), name="condition", breaks=c("A", "B", "C"), labels = c("easy", "medium", "hard"))

现在,另外我认为我需要设置线型,但我不知道是否使用scale_linetype_manual,scale_linetype_discrete等等 . 另外,我不知道如何使用正确的功能 .

任何人都可以帮我解决这个问题吗?那样就好了!

Ps:我已经尝试了各种各样的东西,但是R或者R给我一个颜色指定为预期的情节,但是线型不会改变,但保持稳定,或者它给我错误消息,如

Fehler in grid.Call.graphics(L_polygon, x$x, x$y, index) : 
ungültiger Linientyp: muss Länge 2, 4, 6, oder 8 haben

我想用英语应该是这样的

Error in grid.Call.graphics(L_polygon, x$x, x$y, index) :
invalid linetype: must be length 2, 4, 6, or 8

2 回答

  • 0

    似乎你所缺少的只是 aes() 中的 linetype = condition . 此外,您的 scale_colour_manual 调用似乎是错误的:您只提供两个值而不是三个 . 要使比例正确,您可以使用 scale_linetype_discrete() 进行自动缩放,或使用 scale_linetype_manual() 手动设置线型 . 这是一个例子:

    #
    DFplotlong <- read.table(text='subject iq      condition RT
    1       98      A         312
    1       98      B         354
    1       98      C         432
    2       102     A         134
    2       102     B         542
    2       102     C         621', header=TRUE)
    #
    ggplot(DFplotlong, aes(iq, RT, colour = condition, linetype = condition)) +
      geom_point() +
      geom_smooth(method = lm, fullrange = TRUE, alpha = .15) +
      theme_bw() +
      labs(x = "iq", y = "reaction times") +
      scale_colour_manual(values=c("#999999","#000000", "#900009"),
                         name="condition", 
                         breaks=c("A", "B", "C"), 
                         labels = c("easy", "medium", "hard")) +
      scale_linetype_discrete(name="condition", 
                              breaks=c("A", "B", "C"), 
                              labels = c("easy", "medium", "hard"))
    

    enter image description here

  • 4
    DFplotlong <- read.table(header = TRUE, text = "
      subject iq      condition RT
      1       98      1         312
      1       98      2         354
      1       98      3         432
      2       102     1         134
      2       102     2         542
      2       102     3         621
      3       105     1         137
      3       105     2         545
      3       105     3         624
      ")
    
    DFplotlong$condition <- factor(DFplotlong$condition)
    
    ggplot(data=DFplotlong, aes(iq, RT, colour=condition, linetype=condition)) +
      geom_smooth(method = lm, fullrange = TRUE) +
      theme_bw() +
      labs(x = "iq", y = "reaction times")
    

相关问题