Open In App

R - Line Graphs

Last Updated : 13 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A line graph is a type of chart that helps us visualize data through a series of points connected by straight lines. It is commonly used to show changes over time, making it easier to track trends and patterns. In a line graph, we plot data points on the X and Y axes and connect them with lines, which helps us understand how values move over time or across categories.

Creating Line Graphs in R

To create a line graph in R, we use the plot() function. This function allows us to customize the graph with various parameters like the type of plot, color, labels, and titles.

Syntax:

plot(v, type, col, xlab, ylab, main)

  • v: A vector containing the numeric values to be plotted.
  • type: Specifies the type of graph ("p" only points, "l" only lines, "o" both points and lines).
  • xlab: Label for the x-axis.
  • ylab: Label for the y-axis.
  • main: Title of the chart.
  • col: Specifies the color for the points and lines.

1. Creating a Simple Line Graph

To create a simple line graph, we use the plot() function with the required parameters. Below is an example where we specify the vector of data and use the argument type = "o" to display both points and lines.

Example:

R
v <- c(17, 25, 38, 13, 41)
plot(v, type = "o")

Output:

1
Simple Line Graph

2. Customizing Line Graphs in R

We can make our line graph more informative and visually appealing by adding a title, labels for the axes, and changing the colors of the lines and points.

Example:

In this example, we customize the graph by:

  • Coloring the line and points green.
  • Labeling the x-axis as "Month".
  • Labeling the y-axis as "Articles Written".
  • Adding the title "Articles Written Chart" to the graph.
R
v <- c(17, 25, 38, 13, 41)
plot(v, type = "o", col = "green", xlab = "Month", ylab = "Articles Written", main = "Articles Written Chart")

Output:

2
Customizing Line Graph

3. Plotting Multiple Lines in a Line Graph

We can also create line graphs that display multiple data series, making it easier to compare trends across different datasets. To do this, we add more lines using the lines() function.

Example:

In this example:

  • The first line (v) is plotted in red.
  • The second line (t) is plotted in blue.
  • The third line (m) is plotted in green.
R
v <- c(17, 25, 38, 13, 41)
t <- c(22, 19, 36, 19, 23)
m <- c(25, 14, 16, 34, 29)

plot(v, type = "o", col = "red", xlab = "Month", ylab = "Articles Written", main = "Articles Written Chart")
lines(t, type = "o", col = "blue")
lines(m, type = "o", col = "green")

Output:

3
Plotting Multiple Lines

This way, we can compare the trends of all three data series on the same graph.


Practice Tags :

Similar Reads