Matplotlib - Line Plots



A line plot is a type of graph that displays data points called markers connected by straight line segments. It is generally used to visualize the relationship between two variables; one variable on the x-axis and another on the y-axis.

Line plots are useful for showing trends, patterns, or fluctuations in data over a continuous interval or time. For instance, let us create a graph where we have the population data of a city over several years. The x-axis will represent the years, and the y-axis will represent the population in thousands −

Line Plots

Line Plots in Matplotlib

We can use the plot() function in Matplotlib to draw a line plot by specifying the x and y coordinates of the data points. This function is used to create line plots, which are graphical representations of data points connected by straight lines.

The Plot() Function

The plot() function takes the x and y coordinates of the data points as an input and returns a line plot based on those coordinates.

Following is the syntax of plot() function in Matplotlib −

matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)

Where,

  • *args represents the positional arguments.
  • scalex and scaley are Boolean values that control whether the x-axis and y-axis should be automatically adjusted to fit the data.
  • data allows you to pass a DataFrame or similar structure for plotting.
  • **kwargs represents the additional keyword arguments that allow you to customize the appearance of the plot, such as line style, color, markers, etc.

Lets start by drawing a basic line plot.

Creating a Basic Line Plot

A basic line plot in Matplotlib connects data points with a line. For instance, if you have pairs of x and y values, the plot() function helps visualize how y changes with respect to x. By specifying these coordinates, you can create a simple line graph to observe trends or patterns.

Example

In the following example, we are drawing a basic line plot using Matplotlib, where x and y are lists representing data points −

import matplotlib.pyplot as plt
# data points
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 8]
# Create a line plot
plt.plot(x, y)
# Add labels to the axes
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Add a title to the plot
plt.title('Basic Line Plot')
# Display the plot
plt.show()

Output

Following is the output of the above code −

Basic Line Plot

Line plot with Multiple lines

In a line plot with multiple lines using Matplotlib, you can compare and visualize various datasets simultaneously on a single graph. The legend provide labels for each line on the plot, which helps in identifying each line.

Example

The following example determine a plot with two sets of data represented by lines. The legend labels these lines as 'Line 1' and 'Line 2', helping to identify which line corresponds to which dataset −

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [10, 15, 7, 12, 8]
y2 = [8, 12, 6, 10, 15]

plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2', linestyle='--', marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Multiple Lines with Legend')
plt.legend()
plt.show()

Output

After executing the above code, we get the following output −

Multiple Lines with Legend

Example

In this example, we are plotting the lines with the help of numpy array instead of lists to represent our datasets −

import numpy as np
import matplotlib.pyplot as plt
# Data points of line 1
x1 = np.array([1, 2, 3, 4, 5])
y1 = np.array([2, 4, 6, 8, 10])
# Data points of line 2
x2 = np.array([2,
 3, 4, 5, 6])
y2 = np.array([1, 3, 5, 7, 9])
# Data points of line 3
x3 = np.array([1, 2, 3, 4, 5])
y3 = np.array([5, 4, 3, 2, 1])
# Plotting all lines with labels
plt.plot(x1, y1, label='Line 1')
plt.plot(x2, y2, label='Line 2')
plt.plot(x3, y3, label='Line 3')
# Adding legend, x and y labels, and title for the lines
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Multiple Line Plot')
# Displaying the plot
plt.show()

Output

We get the output as shown below −

Multiple Lines with numpy

Creating Customized Line Plot

In a customized line plot using Matplotlib, you can control the appearance by specifying details like color, linestyle, and markers, enhancing the visual representation of data −

  • Color − You can choose a color for the line, such as 'red' or '#FF0000' (hexadecimal RGB value).
  • Linestyle − It determines the pattern of the line, whether it is solid ('-'), dashed ('--'), dotted (':'), or something else.
  • Markers − These are symbols placed at data points. They can be customized with various shapes, such as circles ('o'), squares ('s'), or stars ('*').

Example

In here, we are retrieving a line plot with a green dashed line, circular markers, and a labeled legend −

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 8]

plt.plot(x, y, color='green', linestyle='--', marker='o', label='Data Line')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Customized Line Plot')
plt.legend()
plt.show()

Output

Output of the above code is as follows −

Customized Line Plot

Line plot with customized axes limits

You can also customize axes limits of a line plot using Matplotlib by defining the range of values for the x and y axes. This enables you to focus on specific portions of the data for a more detailed view.

We can customize axes limits using the functions plt.xlim() and plt.ylim() for the x-axis and y-axis respectively.

Following is the basic syntax of the xlim() function −

plt.xlim(left, right)

Where, left is the leftmost value of the x-axis and rightis the rightmost value of the x-axis.

Similarly, you can use the ylim() function for the y-axis to set specific limits.

Example

Now, we are using the xlim() and ylim() functions to set the range of the x-axis as (0, 10) and y-axis as (0, 20) and ensure that only values within this specified range are displayed −

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 8]

plt.plot(x, y, marker='o', linestyle='-', color='blue', label='Data Line')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Customized Axes Limits')
plt.legend()
# Set x-axis limits
plt.xlim(0, 6)
# Set y-axis limits
plt.ylim(0, 20)  
plt.show()

Output

The output obtained is as shown below −

Customized Axes Limits
Advertisements