Matplotlib

Line Plots


Line plots

This page covers a matplotlib line plots tutorial.

A line plot, also known as a line chart or line graph, is a type of data visualisation. It displays data points as a series of connected line segments. Also, it is commonly used to represent continuous data over a continuous interval or time period.

There are 2 axes in a line plot, x and y. The x-axis typically represents the independent variable (e.g., time, distance, category), while the y-axis represents the dependent variable (e.g., quantity, value, frequency). Each data point is plotted as a marker at the corresponding x and y coordinates. The markers are connected by straight lines, in order to show the trend or relationship between the data points.

Why use line plots?

Line plots are particularly useful for visualising trends, patterns, and changes in data over time or across different categories. They provide a clear and intuitive way to comprehend the relationship between variables. In addition, they offer methods helping identify any underlying patterns or correlations.

Their usage is widely spread across various fields for analysing and presenting data. Fields such as science, finance, economics, engineering, and social sciences. Line plots are versatile and can accommodate various types of data, including continuous, discrete, and categorical data.

Implementation

Creating line plots in matplotlib is straightforward. The main function for plotting line plots is plot().

  1. Import library
  2. Create or add data
  3. Plot data
  4. Add customisations
  5. Display data

For example, let’s create a sample data and add labels.

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# line plot
plt.plot(x, y)

# labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')

# Show plot
plt.show()
matplotlib-line-plot

We can further customise the line plot. We specify additional parameters through the plot() method. Let’s customise line colour, line style, marker size, and marker style. We cover some basic formatting changes for explanatory purposes, but Matplotlib offers many more customisations. For more information regarding customisation, please refer to this tutorial.

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# line plot
plt.plot(x, y, c="purple", ls="--", marker="D", ms=9)

# labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')

# Show plot
plt.show()
matplotlib-line-plot-customise

This is an original line plots tutorial. Created by aicorr.com.

Next: Scatter Plots