How to create a line chart in R?

A line chart, also known as a time plot, is a powerful visualization tool used to display trends over a specific time period. It consists of data points connected by straight lines, effectively representing the progression of the data points over time. Line charts are particularly valuable for visualizing time series data and finding patterns or trends in various fields, including stock market analysis, temperature and weather monitoring, health monitoring, economic indicators, and many more.

Dataset description

Before we dive into creating a line chart in R, let’s take a moment to understand the dataset we’ll use as an example. The "AirPassengers" dataset is one of the pre-existing datasets available in R, designed for practice and learning purposes. It contains the total monthly count of airline passengers from 19491949 to 19601960.

Creating the line chart

To create a line chart in R, we’ll first load the "AirPassengers" dataset using the datasets library. We can install this library by running install.packages("datasets") in R. Then, we can use the following code to load the dataset:

# Load the required library (if not already loaded)
library(datasets)
# Load the dataset
data("AirPassengers")

Once the dataset is loaded, we can use the plot() function to create the line chart. The following code will generate a line chart of the monthly airline passenger data:

# Create a line chart
plot(AirPassengers,
type = "l", # "l" for line chart
col = "red", # Line color
lwd = 2, # Line width
xlab = "Year", # Label for x-axis
ylab = "Number of Passengers", # Label for y-axis
main = "Monthly Airline Passengers") # Title for the plot
# Add a legend to the plot
legend("topleft", # Position of the legend
legend = "Passenger Data", # Text for the legend
col = "blue", # Color of the legend line
lwd = 2) # Width of the legend line
# Add gridlines to the plot
grid()

Code explanation

  • Lines 2–3: We use the plot() function with the argument type = "l" to specify that we want to create a line chart.

  • Lines 4–5: The col parameter sets the color of the line to "red", and lwd sets the line width to 2 for better visibility.

  • Lines 6–8: The xlab, ylab, and main parameters are used to label the x-axis, y-axis, and add a title to the plot, respectively.

  • Lines 11–14: The legend() function is employed to add a legend to the plot, placing it in the top-left corner and labeling it as "Passenger Data" with a blue line of width 2.

  • Line 17: The grid() function is used to add gridlines to the plot.

Now the we know how to create our own line charts in R, we can explore and interpret data patterns effectively.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved