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.
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 to .
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 datasetdata("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 chartplot(AirPassengers,type = "l", # "l" for line chartcol = "red", # Line colorlwd = 2, # Line widthxlab = "Year", # Label for x-axisylab = "Number of Passengers", # Label for y-axismain = "Monthly Airline Passengers") # Title for the plot# Add a legend to the plotlegend("topleft", # Position of the legendlegend = "Passenger Data", # Text for the legendcol = "blue", # Color of the legend linelwd = 2) # Width of the legend line# Add gridlines to the plotgrid()
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