【问题标题】:Coloring line segments in ggplot2ggplot2中的着色线段
【发布时间】:2016-01-28 02:31:44
【问题描述】:

假设我有一个学生在考试中的分数的以下数据。

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()

有什么想法吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我可能会以不同的方式处理这个问题,并改用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")
    

    【讨论】:

    • 首先,感谢您展示嵌入功能。我在做这样的工作人员的时间更长。我想过 line_segment 但我不能像你那样处理它。完美,感谢您的解决方案。
    • 嗨@joran 可以用geom_line 做到这一点吗?
    【解决方案2】:

    默认情况下,ggplot2 根据映射到因子的美学对数据进行分组。您可以通过显式设置组来覆盖此默认值,

      last_plot() + aes(group=NA)
    

    【讨论】:

    • 然而,这并不能解决要为哪些片段着色的问题。 @joran 的答案是正确的方法。
    • 嗯,实际上这就是我最初想要的,在你的解决方案之后,我认为我应该改变我的数据结构。感谢您显示覆盖选项..
    • @baptise 我实际上尝试稍微改变数据结构。将NA 放在df$resp 的末尾而不是像这样开始:resp = c(sample(c("Correct","Incorrect"),10,replace=TRUE),NA) 也解决了我的问题。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多