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

时间:2014-12-02 13:52:51

标签: r ggplot2

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

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给了我一个颜色按预期指定的情节,但是线型不会改变,但保持稳定,或者它给我错误信息,如

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 :(得分:4)

似乎你所缺少的只是linetype = condition参数中的aes()。此外,您的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

答案 1 :(得分:0)

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")
相关问题