rplot

line zigzags in plot after using ifelse


I am trying to plot temperature change as a function of time over one day. I have a column 'Hour' 0-23. For further calculations, I need it to be in a 1-24 range.

Here is my code:

df <- list(datetime = c("2023-01-01", "2023-01-01 01:00:00", 
"2023-01-01 02:00:00", "2023-01-01 03:00:00", "2023-01-01 04:00:00", 
"2023-01-01 05:00:00", "2023-01-01 06:00:00", "2023-01-01 07:00:00", 
"2023-01-01 08:00:00", "2023-01-01 09:00:00", "2023-01-01 10:00:00", 
"2023-01-01 11:00:00", "2023-01-01 12:00:00", "2023-01-01 13:00:00", 
"2023-01-01 14:00:00", "2023-01-01 15:00:00", "2023-01-01 16:00:00", 
"2023-01-01 17:00:00", "2023-01-01 18:00:00", "2023-01-01 19:00:00", 
"2023-01-01 20:00:00", "2023-01-01 21:00:00", "2023-01-01 22:00:00", 
"2023-01-01 23:00:00"), Hour = c(24, 1, 2, 3, 4, 5, 6, 7, 8, 
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23), temp = c(15, 
17, 17, 15, 14, 17, 18, 20, 22, 25, 18, 17, 18, 17, 15, 14, 14, 
15, 13, 12, 11, 10, 11, 11), row.names = c(NA, 24L), class = "data.frame")

plot(temp ~ Hour, data = df, type = "l")

df$Hour <- ifelse(df$Hour == 0, 24, df$Hour)

enter image description here


Solution

  • You want temp ordered by hour.

    > plot(temp[order(Hour)] ~ Hour[order(Hour)], data = df, type = "l")
    

    Or

    > df |> sort_by(~Hour) |> with(plot(temp ~ Hour, type='l'))
    

    enter image description here


    Data:

    Assuming, OP dput failed.

    > df |> dput()
    structure(list(datetime = c("2023-01-01", "2023-01-01 01:00:00", 
    "2023-01-01 02:00:00", "2023-01-01 03:00:00", "2023-01-01 04:00:00", 
    "2023-01-01 05:00:00", "2023-01-01 06:00:00", "2023-01-01 07:00:00", 
    "2023-01-01 08:00:00", "2023-01-01 09:00:00", "2023-01-01 10:00:00", 
    "2023-01-01 11:00:00", "2023-01-01 12:00:00", "2023-01-01 13:00:00", 
    "2023-01-01 14:00:00", "2023-01-01 15:00:00", "2023-01-01 16:00:00", 
    "2023-01-01 17:00:00", "2023-01-01 18:00:00", "2023-01-01 19:00:00", 
    "2023-01-01 20:00:00", "2023-01-01 21:00:00", "2023-01-01 22:00:00", 
    "2023-01-01 23:00:00"), Hour = c(24, 1, 2, 3, 4, 5, 6, 7, 8, 
    9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23), temp = c(15, 
    17, 17, 15, 14, 17, 18, 20, 22, 25, 18, 17, 18, 17, 15, 14, 14, 
    15, 13, 12, 11, 10, 11, 11)), row.names = c(NA, -24L), class = "data.frame")