Home > OS >  Convert data frame to time series for plotting
Convert data frame to time series for plotting

Time:06-25

I have the dataframe:

 year   sum1
   <chr> <dbl>
 1 1979      4
 2 1980     14
 3 1981     14
 4 1982     13
 5 1983      6
 6 1984     15
 7 1985     15
 8 1986      7
 9 1987     10
10 1988     12

and I would like to convert it to time series in order to make a plot. Any idea?

foo

CodePudding user response:

You only need to convert the year to numeric rather than character

DF2 <- transform(DF, year = as.numeric(year))
plot(DF2, type = "l", lwd = 2, lty = 2, col = "blue", 
  xlab = "year", ylab = "value", main = "my title")

If you do want to convert it to a time series then convert it to a zoo series and use classic graphics or ggplot2 (autoplot).

library(zoo)

z <- read.zoo(DF, FUN = as.numeric)

plot(z, type = "l", lwd = 2, lty = 2, col = "blue", 
  xlab = "year", ylab = "value", main = "my title")

library(ggplot2)
autoplot(z, linetype = I("dashed"), lwd = I(1.5), col = I("blue"))   
  xlab("year")   
  ylab("value")   
  ggtitle("my title")

screenshot

Note

Lines <- "year   sum1
 1 1979      4
 2 1980     14
 3 1981     14
 4 1982     13
 5 1983      6
 6 1984     15
 7 1985     15
 8 1986      7
 9 1987     10
10 1988     12"
DF <- read.table(text = Lines, colClasses = c(year = "character"))

CodePudding user response:

Convert as.xts and plot. First complete the dates with January 1.

my_ts <- xts::as.xts(dat$sum1, order.by=as.Date(paste0(dat$year, '-01-01')))
plot(my_ts)

enter image description here


Data:

dat <- structure(list(year = 1979:1988, sum1 = c(4L, 14L, 14L, 13L, 
6L, 15L, 15L, 7L, 10L, 12L)), class = "data.frame", row.names = 1979:1988)

CodePudding user response:

We could use tsibble package to transfrom dataframe to times series obejct:

library(tsibble)
library(fable)
df %>% 
  as_tsibble(index = year) %>% 
  autoplot(vars(sum1))

enter image description here

  • Related