Search code examples
rplottime-seriestimeserieschart

How can I plot a time series that shows only days on x-axis?


I want to draw this time series plot using R.

Line plot

My dataset is a time series that includes days, hours and minutes. I want the plot to show only the day of the week. When I use a normal plot(x,y) i get a box plot and I am not able to figure out the type of this plot. Can anyone help me in figuring out the plot and which function can be used to get such a plot.

Head of actual data:

head(data)
#        Date     Time Global_active_power Global_reactive_power Voltage
#1 2006-12-16 17:24:00               4.216                 0.418  234.84
#2 2006-12-16 17:25:00               5.360                 0.436  233.63
#3 2006-12-16 17:26:00               5.374                 0.498  233.29
#4 2006-12-16 17:27:00               5.388                 0.502  233.74
#5 2006-12-16 17:28:00               3.666                 0.528  235.68
#6 2006-12-16 17:29:00               3.520                 0.522  235.02

#  Global_intensity Sub_metering_1 Sub_metering_2 Sub_metering_3
#1             18.4              0              1             17
#2             23.0              0              1             16
#3             23.0              0              2             17
#4             23.0              0              1             17
#5             15.8              0              1             17
#6             15.0              0              2             17

Minimally reproducible dataset:

set.seed(123)
data <- data.frame(Date = as.Date(rep(c("2006-06-16", "2006-06-17"), each = 1440)),
  Time = format(as.difftime(0:1439, units = "mins") + as.POSIXct("2006-06-16"), "%H:%M"),
  Global_active_power = cumsum(rnorm(2880, 0.02, 0.02) * rep(rep(c(1, -1), 4), 2880 / 8)))

At this stage, I've tried the following:

x <- weekdays(data$Date)
y <- data$Global_active_power

plot(x, y)

but I get a boxplot.


Solution

  • Maybe this is what you want:

    set.seed(123)
    data <- data.frame(Date = as.Date(rep(c("2006-06-16", "2006-06-17"), each = 1440)),
                       Time = format(as.difftime(0:1439, units = "mins") + 
                                     as.POSIXct("2006-06-16"), "%H:%M"),
                       Global_active_power = cumsum(rnorm(2880, 0.02, 0.02) *
                                             rep(rep(c(1, -1), 4), 2880 / 8)))
    
    data$datetime <- as.POSIXct(paste(data$Date,data$Time),tz="UCT")
    plot(data$datetime,data$Global_active_power,type="l")
    

    Here is the plot: enter image description here