Matplotlib Basic Line Plots

MatplotlibBeginner
Practice Now

Introduction

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It's one of the most popular data visualization libraries and is essential for any data scientist or analyst working with Python.

A line plot is one of the most basic and widely used types of plots. It displays information as a series of data points called 'markers' connected by straight line segments. It is often used to visualize a trend in data over intervals of time – a time series – thus the line is often drawn chronologically.

In this lab, you will learn how to create a simple line plot from scratch. We will cover the entire process: preparing the data, plotting it, adding descriptive labels to the axes, and finally, saving the plot as an image file that you can view directly in the LabEx environment.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 84% completion rate. It has received a 100% positive review rate from learners.

Prepare x and y data lists

In this step, we will prepare the data for our plot. Before you can visualize anything, you need data. For a simple 2D line plot, you need two sets of data: one for the x-axis (the horizontal axis) and one for the y-axis (the vertical axis).

We will use Python lists to store our data. Let's create a simple dataset representing population growth over a few years.

First, open the main.py file located in the ~/project directory from the file explorer on the left. The file already contains the necessary import statement.

Now, add the following code to main.py to create two lists, x and y.

import matplotlib.pyplot as plt

## Data for plotting
x = [2018, 2019, 2020, 2021, 2022]
y = [10, 12, 15, 18, 22]

Here, x represents the years, and y represents the population in millions for each corresponding year. These two lists will serve as the coordinates for our line plot.

Plot line using plt.plot(x, y)

In this step, we will use the data we prepared to create the actual plot. Matplotlib's pyplot module, which we imported as plt, provides a function called plot() that is perfect for this task.

The plt.plot() function takes two main arguments: the data for the x-axis and the data for the y-axis. It will then draw a line connecting the points defined by these coordinates.

Add the following line to your main.py script, right after the data lists you created in the previous step.

import matplotlib.pyplot as plt

## Data for plotting
x = [2018, 2019, 2020, 2021, 2022]
y = [10, 12, 15, 18, 22]

## Create the plot
plt.plot(x, y)

This single line of code tells Matplotlib to create a line plot using the x and y lists as coordinates. However, if you run the script now, you won't see anything yet. We still need to add labels and explicitly save the plot to a file.

Add x-axis label with plt.xlabel()

In this step, we will add a label to the x-axis. A plot without labels is often meaningless because the viewer doesn't know what the axes represent. It's a crucial part of creating clear and informative visualizations.

Matplotlib provides the plt.xlabel() function to add a label to the x-axis. You simply pass the desired label as a string to this function.

Let's add a label for the 'Year' to our plot. Add the following line to your main.py script after the plt.plot() call.

import matplotlib.pyplot as plt

## Data for plotting
x = [2018, 2019, 2020, 2021, 2022]
y = [10, 12, 15, 18, 22]

## Create the plot
plt.plot(x, y)

## Add x-axis label
plt.xlabel("Year")

Now, the horizontal axis of our plot will be clearly marked as 'Year'.

Add y-axis label with plt.ylabel()

In this step, we will add a label to the y-axis, completing the basic labeling of our plot. Just like the x-axis, the y-axis needs a descriptive label so viewers can understand the data.

The function for this is plt.ylabel(), which works exactly like plt.xlabel(). You pass the label text as a string.

Let's add a label for 'Population' to our plot. Add the following line to your main.py script, right after the plt.xlabel() call.

import matplotlib.pyplot as plt

## Data for plotting
x = [2018, 2019, 2020, 2021, 2022]
y = [10, 12, 15, 18, 22]

## Create the plot
plt.plot(x, y)

## Add x-axis label
plt.xlabel("Year")

## Add y-axis label
plt.ylabel("Population (in millions)")

With both axes labeled, our plot is now much more understandable.

Show plot using plt.show()

In this final step, we will generate and view our plot. In a typical desktop environment, you might use plt.show() to display the plot in a new window. However, in a web-based environment like LabEx, we cannot open GUI windows.

Instead, we will save the plot to an image file using the plt.savefig() function. This function saves the current figure to a file in your project directory.

Add the following line to the end of your main.py script. This will save the plot as a PNG image named line_plot.png.

import matplotlib.pyplot as plt

## Data for plotting
x = [2018, 2019, 2020, 2021, 2022]
y = [10, 12, 15, 18, 22]

## Create the plot
plt.plot(x, y)

## Add x-axis label
plt.xlabel("Year")

## Add y-axis label
plt.ylabel("Population (in millions)")

## Save the plot to a file
plt.savefig("line_plot.png")

Now, open a terminal in the WebIDE (you can use the + icon in the terminal panel or the menu Terminal > New Terminal). Run your script with the following command:

python3 main.py

After the command finishes, you will see a new file named line_plot.png appear in the file explorer on the left. Double-click on line_plot.png to open it and see your completed line plot!

Line plot

Summary

Congratulations! You have successfully created and saved your first line plot using Matplotlib.

In this lab, you learned the fundamental workflow for creating a basic plot:

  1. Prepare Data: You created Python lists to hold the data for your x and y axes.
  2. Plot Data: You used plt.plot() to generate the line plot from your data.
  3. Add Labels: You made the plot informative by adding labels with plt.xlabel() and plt.ylabel().
  4. Save the Plot: You learned to use plt.savefig() to save your visualization to a file, which is essential in non-GUI environments.

This is just the beginning of what you can do with Matplotlib. You can now build on these skills to create more complex and customized visualizations. Keep exploring!