Using ggplot with Time Series Data in R Programming

Pierre DeBois
4 min readSep 30, 2022

Time series data in R programming is treated as a special data object. That can create some complications when you’re trying to print out a time series object.

First and foremost you can use the plot function that’s built into our to plot your time series object. But the plot function does have some limitations in terms of the appearance of the graph and maybe combinations with data that you may have intended with this time series object.

The natural choice would be to turn to the ggplot2 library. The ggplot2 library, as I explained in my post on data visualization usually provides a number of options in its attributes to customize visualizations and make adjustments. Moreover, there is an ecosystem of libraries that have been built around the ggplot2 library.

But the ggplot() function does require the data object to be a data frame. This means that you must take your time series data and convert it into a data frame object before applying the features and functions of the ggplot2 library. This can seem a little complicated but there are some tips that can keep the steps easy.

Use seq() to create a column of dates

First look at using the sequence function to create dates in a familiar R programming format alongside your observations. To do this you combine the sequence function with the as.date() function to create a series of date formats.

The as.date() function requires a date format to be set in the argument. The format sets the number of days or weeks of the observations of your time series. This is the function you want to “tell R” to treat the observations as a date with a certain structure.

In the image above we are creating a sequence of dates, just as an example, so the as.date() is nested in the sequence function, telling the sequence to create a set of dates in the format = %m/%d/%Y , with by = 90 number of days, and length (=10) to set the object length. When I enter the length as 10, I am indicating that 10 dates will be set 90 days apart. The output looks like the following image:

--

--

Pierre DeBois

#analytics |#datascience |#JS |#rstats |#marketing services for #smallbiz | #retail | #nonprofits Contrib @CMSWire @smallbiztrends #blackbusiness #BLM