Search code examples
rplotgraphgrouping

Plotting with 2 colors per group


I have a data as follows:

data<-data.frame(ymdhms=c(20230301000000,20230301000010,20230301000020,20230301000030,20230301000040,
                          20230301000050,20230301000100,20230301000110),
                 switch=c(0,0,0,1,0,0,1,0),
                 power=c(20,21,22,23,20,19,29,28))

ymdhms means year, month, day, hour, minute, and second. For example, 20230301000000` means 00:00:00 , March 1st, 2023.

ymdhms has the values of 10 seconds time intervals. For the switch column, 1 means that switch is on and 0 means that switch is off. What I want to do is plot powerwith respect to ymdhms. So y-axis should be power and x-axis should be time.I want x-axis to be represented as the time order and only indicate how many seconds have passed. I also want to visually differentiate whether the switch is on or off. If the switch is off, I want to color the area as red. If the switch is on, I want to color the area as green.

Can you suggest a nice way to visualize what I want to do?


Solution

  • I can try to plot one simple line plot.

    First, load the packages needed

    library(ggplot2)
    library(lubridate)
    

    Then make a dataframe:

    data <- data.frame(ymdhms=c(20230301000000,20230301000010,20230301000020,20230301000030,20230301000040,20230301000050,20230301000100,20230301000110),switch=c(0,0,0,1,0,0,1,0), power=c(20,21,22,23,20,19,29,28))
    

    Next, convert the date-time data into POSIXct format

    # ymdhms to POSIXct
    data$timestamp <- ymd_hms(data$ymdhms)
    

    Next, create a status 'Switch'. This will help in coloring the data in plot

    # status variable 
    data$switchStatus <- ifelse(data$switch == 1, "on", "off")
    

    Finally, make plot from the data

    # plot
    ggplot(data, aes(x = timestamp, y = power, color = switchStatus)) +
      geom_line() +
      geom_rect(aes(xmin = lag(timestamp, default = first(timestamp)),
                    xmax = timestamp, ymin = -Inf, ymax = Inf,
                    fill = switchStatus), alpha = 0.2, inherit.aes = FALSE) +
      scale_fill_manual(values = c("red", "green")) +
      xlab("Time (seconds)") + ylab("Power") +
      theme_classic()
    

    This will produce something like below:

    enter image description here

    If you want, you could also plot variants such as step chart etc.

    Let me know if this helped.

    Step Chart:

    # step chart
    ggplot(data, aes(x = timestamp, y = power, group = 1)) +
      geom_step(aes(color = factor(switch)), direction = "hv") +
      scale_color_manual(values = c("red", "green")) +
      labs(x = "Time", y = "Power", color = "Switch")
    

    enter image description here