1
library(ggplot2)
data = data.frame("person"=rep(1:2,4),
                  "time" = rep(1:4, 2),
                  "scores" = c(5,7,9,11,
                               8,12,13,14))
data = data[order(data$person),]

ggplot(data,aes(time,scores,group=as.factor(person))) +
  geom_line(color="red")

This code here will plot the two lines in red. I understand it how to change the color of a line. But~ how do I edit code so values of 8 and more are colored blue?

edit

eipi10 provided a great answer but I realize it only works when you have a single if statement, What if you have data such as

library(ggplot2)
data = data.frame("person"=c(rep(1,4), rep(2,4)),
                  "time" = rep(1:4, 2),
                  "scores" = c(5,7,9,11,
                               8,12,13,14),
                  "type" = c(1,2,2,3,
                             1,1,3,3))
data = data[order(data$person),]

And you want: 1. Red if type = 1 2. Blue if type = 2 3. Green if type = 3

Also I changed this question. The original is above and then I added this extra pieces which some could be very useful for.!

tjebo
  • 21,977
  • 7
  • 58
  • 94
bvowe
  • 3,004
  • 3
  • 16
  • 33
  • 3
    `geom_line(aes(color=scores > 8)) + scale_colour_manual(values=c(\`TRUE\`="blue", \`FALSE\`="red"))` – eipi10 Nov 27 '19 at 16:36
  • `geom_line(colour = ifelse(data$scores > 8, "blue", "red"))` – d.b Nov 27 '19 at 16:40
  • @d.b I think eipi10's solution may be safer because it does not use `$` (which could potentially not match the order of the data frame which is being plotted). Anyways. It's a dupe question... – tjebo Nov 27 '19 at 16:45
  • @eipi10 check [this answer](https://stackoverflow.com/a/11838396/7941188) from mnel, similar to yours, but with the elegant use of `setNames` – tjebo Nov 27 '19 at 16:49
  • as to your edit - if you want to color by your type, just use ggplots basic syntax `geom_line(aes(color = type))+scale_color_manual(values = etc)` – tjebo Nov 27 '19 at 21:39

0 Answers0