ggplot2 中的线段着色

2024-03-26

假设我有以下学生测试成绩的数据。

set.seed(1)
df <- data.frame(question = 0:10,
                 resp = c(NA,sample(c("Correct","Incorrect"),10,replace=TRUE)), 
                 score.after.resp=50)
for (i in 1:10) {
  ifelse(df$resp[i+1] == "Correct",
         df$score.after.resp[i+1] <- df$score.after.resp[i] + 5, 
         df$score.after.resp[i+1] <- df$score.after.resp[i] - 5)
}
df

.

   question      resp score.after.resp
1         0      <NA>               50
2         1   Correct               55
3         2   Correct               60
4         3 Incorrect               55
5         4 Incorrect               50
6         5   Correct               55
7         6 Incorrect               50
8         7 Incorrect               45
9         8 Incorrect               40
10        9 Incorrect               35
11       10   Correct               40

我想得到下图:

library(ggplot2)
ggplot(df,aes(x = question, y = score.after.resp)) + geom_line() + geom_point()

我的问题是:我想根据学生的反应给这条线的各个部分着色。如果正确(增加)线段将为绿色,如果错误响应(减少)线段应为红色。 我尝试了以下代码但没有成功:

ggplot(df,aes(x = question, y = score.after.resp, color=factor(resp))) + 
  geom_line() + geom_point()

有任何想法吗?


我可能会以不同的方式处理这个问题,并使用geom_segment反而:

df1 <- as.data.frame(with(df,cbind(embed(score.after.resp,2),embed(question,2))))
colnames(df1) <- c('yend','y','xend','x')
df1$col <- ifelse(df1$y - df1$yend >= 0,'Decrease','Increase')

ggplot(df1) + 
    geom_segment(aes(x = x,y = y,xend = xend,yend = yend,colour = col)) + 
    geom_point(data = df,aes(x = question,y = score.after.resp))

简要说明:

我在用着embed将 x 和 y 变量转换为每个线段的起点和终点,然后简单地添加一个变量来指示每个线段是向上还是向下。然后我使用之前的数据框来添加原始点本身。

或者,我想你可以使用geom_line像这样的东西:

df$resp1 <- c(as.character(df$resp[-1]),NA)
ggplot(df,aes(x = question, y = score.after.resp, color=factor(resp1),group = 1)) + 
    geom_line() + geom_point(color = "black")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ggplot2 中的线段着色 的相关文章

随机推荐