Search code examples
rplot

Plot different line chart with R


I have a dataset like this:

number <- c(0,1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,6,7,8,0,1,2,3,4,5,6,7,8,9)
val <- c(19,20,9,17,2,2,3,9,19,4,15,14,18,8,5,13,9,15,3,16,1,15,13,10,7,7,9,15,14,12)
m <- data.frame(number, val)

I want to draw different line plot, following "number" column, so I want a specific plot every time number is equal to 0. I mean:

  • first plot for the first 0 to 10
  • second plot for the second 0 to 8
  • third plot for the third 0 to 9

How can I do whit R?


Solution

  • Using cumsum on diff in INDEX of by.

    > par(mfrow=c(1, sum(m$number == 0)))
    > by(m$val, cumsum(c(1, diff(m$number) < 0)), plot, type='l') |> invisible()
    

    enter image description here


    Data:

    > dput(m)
    structure(list(number = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 
    1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9), val = c(19, 
    20, 9, 17, 2, 2, 3, 9, 19, 4, 15, 14, 18, 8, 5, 13, 9, 15, 3, 
    16, 1, 15, 13, 10, 7, 7, 9, 15, 14, 12)), class = "data.frame", row.names = c(NA, 
    -30L))