Search code examples
rggplot2linepoint

R: ggplot - plotting a trend line of datapoint with different colors based on group


Assume I have a dataframe df:

Day   Value   Group
1     1       1
2     5       1
3     10      2
4     15      2
5     20      1

I would like to trend a single line on df, x = Day & y = Value, but with each points colored based on Group

Here's a rough illustration for better understanding: Single line trend with colored points

Please advise


Solution

  • You can apply the color= aesthetic to only one layer if needed.

    library(ggplot2)
    ggplot(dat, aes(Day, Value)) +
      geom_line() +
      geom_point(aes(color = factor(Group)), size = 2)
    

    ggplot2

    Data:

    dat <- read.table(header=TRUE, text="
    Day   Value   Group
    1     1       1
    2     5       1
    3     10      2
    4     15      2
    5     20      1")