How to Plot a Time Series in R (With Examples)


Often you may want to plot a time series in R to visualize how the values of the time series are changing over time.

This tutorial explains how to quickly do so using the data visualization library ggplot2.

Basic Time Series Plot in R

Suppose we have the following dataset in R:

#create dataset
df <- data.frame(date = as.Date("2021-01-01") - 0:99,
                 sales = runif(100, 10, 500) + seq(50, 149)^2)

#view first six rows
head(df)

        date    sales
1 2021-01-01 2845.506
2 2020-12-31 2837.849
3 2020-12-30 3115.517
4 2020-12-29 2847.161
5 2020-12-28 3374.619
6 2020-12-27 3182.005

We can use the following code to create a basic time series plot for this dataset using ggplot2:

library(ggplot2)

#create time series plot
p <- ggplot(df, aes(x=date, y=sales)) +
       geom_line()

#display time series plot
p

Basic time series plot in R

Format the Dates on the X-Axis

We can use the scale_x_date() function* to format the dates shown along the x-axis of the plot. This function takes the following arguments:

  • %d: Day as a number between 0 and 31
  • %a: Abbreviated weekday (e.g. “Tue”)
  • %A: Unabbreviated weekday (e.g. “Tuesday”)
  • %m: Month between 0 and 12
  • %b: Abbreviated month (e.g. “Jan”)
  • %B: Unabbreviated month (e.g. “January”)
  • %y: 2-digit year (e.g. “21”)
  • %Y: 4-digit year (e.g. “2021”)
  • %W: Week of the year between 0 and 52

*In order for this function to work, the x-axis variable must be a date variable. If it is not already one, you can quickly convert it to one by using as.Date(variable_name).

The following code shows how to use one of these formats in practice:

p + scale_x_date(date_labels = "%b %Y")

Time series plot with custom dates in R

You can also add more frequent (or infrequent) breaks along the x-axis by using the date_breaks argument. For example, we could display the dates for every two weeks along the x-axis:

p + scale_x_date(date_breaks = "2 week")

Time series with date breaks on x-axis in R

We can also easily angle the x-axis labels by using the following argument:

p + theme(axis.text.x=element_text(angle=50, hjust=1)) 

Angle the x-axis labels in ggplot2

Lastly, we can change the theme, the axes labels, and the title to make the time series plot more visually appealing:

p <- ggplot(df, aes(x=date, y=sales)) +
       geom_line(color="turquoise4") +
       theme_minimal() + 
       labs(x="", y="Sales", title="Total Sales (Past 100 Days)") +
       theme(plot.title = element_text(hjust=0.5, size=20, face="bold"))

p

Time series with custom ggplot theme in R

Additional Resources

A Complete Guide to the Best ggplot2 Themes
The Complete Guide to ggplot2 Titles
How to Create Side-by-Side Plots in ggplot2

2 Replies to “How to Plot a Time Series in R (With Examples)”

  1. I can see how handy ggplot is. Could you still provide an example using base R? I’m new, and just want to get a solid handle on foundations before upgrading.

    1. Hi Michael…Certainly! Using base R graphics is a great way to get a solid foundation in data visualization before moving on to more advanced packages like `ggplot2`. Below is an example of how you can create a few basic plots using base R. We will use the built-in `mtcars` dataset for illustration.

      ### 1. Scatter Plot
      Let’s create a scatter plot of `mpg` (miles per gallon) against `wt` (weight of the car).

      “`r
      # Load the dataset
      data(mtcars)

      # Create a scatter plot
      plot(mtcars$wt, mtcars$mpg,
      main=”Scatter Plot of MPG vs Weight”,
      xlab=”Weight (1000 lbs)”,
      ylab=”Miles Per Gallon (MPG)”,
      pch=19, # Plotting character, 19 is a solid circle
      col=”blue”)
      “`

      ### 2. Histogram
      Next, let’s create a histogram of the `mpg` (miles per gallon) variable.

      “`r
      # Create a histogram
      hist(mtcars$mpg,
      main=”Histogram of Miles Per Gallon”,
      xlab=”Miles Per Gallon”,
      col=”lightgreen”,
      border=”black”)
      “`

      ### 3. Boxplot
      We’ll create a boxplot of `mpg` (miles per gallon) grouped by the number of cylinders (`cyl`).

      “`r
      # Create a boxplot
      boxplot(mpg ~ cyl, data=mtcars,
      main=”Boxplot of MPG by Number of Cylinders”,
      xlab=”Number of Cylinders”,
      ylab=”Miles Per Gallon”,
      col=c(“orange”, “yellow”, “lightblue”))
      “`

      ### 4. Line Plot
      Now, let’s create a line plot of `mpg` over the index of the dataset (essentially, just the row numbers).

      “`r
      # Create a line plot
      plot(mtcars$mpg, type=”o”, # ‘o’ stands for both points and lines
      main=”Line Plot of Miles Per Gallon”,
      xlab=”Index”,
      ylab=”Miles Per Gallon”,
      col=”red”)
      “`

      ### 5. Bar Plot
      Lastly, let’s create a bar plot of the counts of cars with different numbers of cylinders.

      “`r
      # Create a bar plot
      barplot(table(mtcars$cyl),
      main=”Bar Plot of Cylinder Counts”,
      xlab=”Number of Cylinders”,
      ylab=”Frequency”,
      col=c(“purple”, “lightblue”, “pink”))
      “`

      ### Putting It All Together
      You can use these basic plots to explore your data and communicate findings. Base R graphics are powerful and versatile, and getting comfortable with them will provide a strong foundation for understanding more complex visualization tools like `ggplot2`.

      If you need to customize your plots further, you can adjust parameters such as `xlim`, `ylim`, `las` (for axis labels orientation), `cex` (for character expansion), and many others. Here’s an example of a more customized scatter plot:

      “`r
      # Customized scatter plot
      plot(mtcars$wt, mtcars$mpg,
      main=”Customized Scatter Plot of MPG vs Weight”,
      xlab=”Weight (1000 lbs)”,
      ylab=”Miles Per Gallon (MPG)”,
      pch=19,
      col=”darkgreen”,
      xlim=c(1, 6), # Setting x-axis limits
      ylim=c(10, 35), # Setting y-axis limits
      cex=1.5) # Increasing point size
      abline(lm(mpg ~ wt, data=mtcars), col=”red”, lwd=2) # Adding a regression line
      “`

      This should give you a solid start with base R graphics!

Leave a Reply

Your email address will not be published. Required fields are marked *