R: time series plot years and observations in order as they come in dataset

Viewed 118

I have a dataset:

    TimeSeries <- data.frame(date=c("2013","2013","2013","2014","2014","2015","2015","2016", "2016","2017","2017"), 
                  score=c(-0.333, 0.500, 0.000, 0.333, -0.500, 0.777, -0.450, 0.667, -0.011, 0.111, -0.145))

Now I just want to simply plot this as a time series, that shows all observations, every year. I just the code:

ggplot(TimeSeries, aes(x = date, y = score)) + 
  geom_line() + scale_x_discrete(breaks = c(2013,2014,2015,2016))

This gives me the following:

enter image description here

But instead of this, I want the observations from "2013" to be in order as they come in the dataset, in between "2013" and "2014" on the xas. Thus this will be a line going from: -0.333 to 0.500 to 0.000. Same for all other years and observations. They need to be attached to each other, in the order that they come in the dataset. So first of 2013 first, then second, etc. Can anyone help?

2 Answers

I'd suggest making the year and observation into a fractional year measurement so that you can benefit from the convenience of a continuous axis:

library(dplyr)
TimeSeries %>%
  group_by(date) %>%
  mutate(obs_num = row_number(),
         year_dec = as.numeric(date) + (obs_num - 1)/max(obs_num)) %>%
  ungroup() %>%
  
  ggplot(aes(year_dec, score)) +
  geom_line()

enter image description here

You'll find the functions in the lubridate package to be helpful.

Basically what we do is create an artificial date that is based on the year plus the order of the variables. The order is converted to decimal, then added to the year, and converted to an actual date for plotting.

TimeSeries %>% 
  mutate(date = as.numeric(date)) %>% 
  group_by(date) %>% 
  mutate(date_order = row_number()) %>% 
  mutate(n_in_year = n()) %>% 
  mutate(decimal = date_order / n_in_year) %>% 
  mutate(full_date_decimal = date + decimal) %>% 
  mutate(plot_date = date_decimal(full_date_decimal)) %>% 
  mutate(plot_date = as_date(plot_date)) %>% 
  ggplot(aes(x = plot_date, y = score)) +
  geom_line() +
  scale_x_date()

enter image description here

Related