Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to plot line graph in matplotlib

Understanding the Basics of a Line Graph

Before diving into the code, let's first understand what a line graph is. A line graph is a type of chart that displays information as a series of data points, called 'markers', connected by straight line segments. It's a basic and commonly used type of chart that is great for showing trends over intervals—think of it as a way to connect the dots over time or categories.

Setting Up Your Environment

To create a line graph in Python, we will use a library called matplotlib. To use matplotlib, you need to install it. If it's not already installed, you can install it using pip, which is the package installer for Python:

pip install matplotlib

Once installed, you will need to import it into your Python script. The most common way to do this is by importing the pyplot module from matplotlib, which is typically imported as plt for ease of use:

import matplotlib.pyplot as plt

Creating Your First Line Graph

Now that you have matplotlib installed and imported, let's create a simple line graph. We'll start with plotting a list of numbers. Think of these numbers as your 'Y-axis' values, which will be plotted against their corresponding 'X-axis' index values.

# Data for plotting
y_values = [1, 2, 3, 4, 5]

# Plotting the line graph
plt.plot(y_values)
plt.show()

When you run this code, a window will pop up displaying a line graph with five points. The points are connected by lines, starting from the first value (1) and ending at the last value (5).

Customizing the X-Axis

In the previous example, the X-axis was automatically set to [0, 1, 2, 3, 4] because we didn't specify any X values. However, in most cases, you will want to define your own X-axis values. Here's how you can do that:

# X and Y data for plotting
x_values = [10, 20, 30, 40, 50]
y_values = [1, 2, 3, 4, 5]

# Plotting the line graph with custom X-axis
plt.plot(x_values, y_values)
plt.show()

Now the graph will plot the Y values against the X values that you've defined, giving you control over both axes.

Enhancing Your Graph with Labels and a Title

Your graph can be made much more informative by adding labels to the X and Y axes, as well as a title at the top. Here's how:

# X and Y data for plotting
x_values = [10, 20, 30, 40, 50]
y_values = [1, 2, 3, 4, 5]

# Plotting the line graph with labels and a title
plt.plot(x_values, y_values)
plt.title('My First Line Graph')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.show()

The title(), xlabel(), and ylabel() functions allow you to set the title and labels of your graph, making it clearer what your graph represents.

Customizing Line Style and Markers

To make your line graph stand out or to differentiate between multiple lines, you can customize the line style and markers. Let's say you want a dashed line with circle markers:

# X and Y data for plotting
x_values = [10, 20, 30, 40, 50]
y_values = [1, 2, 3, 4, 5]

# Plotting with custom line style and markers
plt.plot(x_values, y_values, linestyle='--', marker='o')
plt.title('Stylish Line Graph')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.show()

By adding linestyle='--' and marker='o' to the plot() function, you've changed the line to a dashed line and added circle markers to each data point.

Plotting Multiple Lines

Sometimes you may want to compare trends by plotting multiple lines on the same graph. You can do this by calling plot() multiple times before calling show().

# Data for plotting
x_values = [10, 20, 30, 40, 50]
y_values1 = [1, 2, 3, 4, 5]
y_values2 = [2, 3, 4, 5, 6]

# Plotting multiple lines
plt.plot(x_values, y_values1, label='Line 1')
plt.plot(x_values, y_values2, label='Line 2')
plt.title('Comparing Two Lines')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.legend()
plt.show()

The legend() function is used to add a legend to the graph, which helps distinguish between the different lines.

Understanding Axes and Figures

In matplotlib, the entire window that pops up with your graph is called a 'Figure', and each graph inside that window is called an 'Axes'. You can have multiple graphs (Axes) in one Figure. Here's how you can create a figure and an axis explicitly:

# Data for plotting
x_values = [10, 20, 30, 40, 50]
y_values = [1, 2, 3, 4, 5]

# Creating figure and axis objects
fig, ax = plt.subplots()

# Plotting on the created axis
ax.plot(x_values, y_values)
ax.set_title('Understanding Axes and Figures')
ax.set_xlabel('X-axis Label')
ax.set_ylabel('Y-axis Label')

# Display the figure
plt.show()

Using subplots() gives you more control over your graph, allowing you to easily customize and manipulate it.

Saving Your Graph

Once you're happy with your graph, you might want to save it to a file. You can do this with the savefig() function:

# Plotting the line graph
plt.plot(x_values, y_values)
plt.title('Graph Ready to be Saved')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')

# Saving the figure
plt.savefig('my_line_graph.png')

The graph will be saved to the same directory as your script, unless you specify a different path.

Conclusion

Creating a line graph in matplotlib is a journey that starts with plotting simple data points and can grow into customizing and refining your visuals to convey the exact message you want. Remember, a graph is worth a thousand words, and with the tools you've learned here, you can tell a compelling story with your data.

As you grow more comfortable with matplotlib, you'll find that the possibilities for customization are vast. You can change colors, styles, scales, and even animate your graphs. The key is to start simple and gradually build up your skills.

Most importantly, have fun with it! Data visualization is an art form. Each graph you make is a reflection of your understanding and creativity. So go ahead and plot away, and watch as the lines you code turn into insights and stories that can be shared with the world.