May Robinson
May Robinson

Reputation: 15

Draw a time series plot using r

I am attempting to draw a time series plot using r. My data look like this:

A tibble: 96 x 2
   interval average_received
     <fctr>            <dbl>
 1     0:00         3.034483
 2     0:30         2.300000
 3     0:45         2.473684
 4     1:30         1.647059
 5    10:00        18.161290
 6    10:15        16.096774
 7    10:30        18.064516
 8    10:45        15.677419
 9    11:00        15.709677

R is reading in interval as a factor. I want it to be a time object in minutes:seconds, then plot it on the x-axis, with average_received on the y-axis. Thanks in advance for your help.

Upvotes: 0

Views: 92

Answers (1)

www
www

Reputation: 39184

Here is one idea. We can add a date to the interval column and then convert the column to POSIXct class. The date will not be shown in the later plot so it could be any dates, which just helps the type conversion. We can then use ggplot2 to plot the data and specify the format on the x-axis.

library(dplyr)
library(ggplot2)
library(lubridate)

dat2 <- dat %>%
  mutate(interval = ymd_hm(paste("2018-05-12", interval, sep = " ")))

ggplot(dat2, aes(x = interval, y = average_received)) +
  geom_line(color = "blue") +
  geom_point(color = "blue") +
  scale_x_datetime(date_breaks = "1 hour", date_labels = "%H:%M") +
  theme_classic()

enter image description here

DATA

dat <- read.table(text = "   interval average_received
                  1     0:00         3.034483
                  2     0:30         2.300000
                  3     0:45         2.473684
                  4     1:30         1.647059
                  5    10:00        18.161290
                  6    10:15        16.096774
                  7    10:30        18.064516
                  8    10:45        15.677419
                  9    11:00        15.709677",
                  header = TRUE, stringsAsFactors = FALSE)

Upvotes: 1

Related Questions