Efficient Line Plotting with Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this tutorial, we will learn how to use the LineCollection function in Matplotlib to efficiently draw multiple lines at once. We will see how to plot multiple lines with different colors and styles, and how to use a masked array to mask some values. We will also learn how to use the ScalarMappable.set_array function to map an array of values to colors.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/matplotlib_config("`Customizing Matplotlib Configurations`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/with_statement -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} matplotlib/line_styles_colors -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} matplotlib/matplotlib_config -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/for_loops -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/list_comprehensions -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/lists -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/tuples -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/importing_modules -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/numerical_computing -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/data_visualization -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} python/build_in_functions -.-> lab-48804{{"`Efficient Line Plotting with Matplotlib`"}} end

Import Libraries

Before we start, we need to import the necessary libraries. We will use matplotlib.pyplot and numpy.

import matplotlib.pyplot as plt
import numpy as np

Create Data

Next, we need to create the data that we will use to plot the lines. We will use numpy to create a 2D array of x and y values.

x = np.arange(100)
ys = x[:50, np.newaxis] + x[np.newaxis, :]

Create Line Collection

Now, we can create a LineCollection object with the LineCollection function. We can set the linewidths, colors, and linestyle parameters to customize the appearance of the lines.

colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

segs = np.zeros((50, 100, 2))
segs[:, :, 1] = ys
segs[:, :, 0] = x

segs = np.ma.masked_where((segs > 50) & (segs < 60), segs)

line_segments = LineCollection(segs, linewidths=(0.5, 1, 1.5, 2),
                               colors=colors, linestyle='solid')

Create Plot

We can now create a plot using matplotlib and add the LineCollection object to the plot using the add_collection method of the Axes object.

fig, ax = plt.subplots()
ax.set_xlim(x.min(), x.max())
ax.set_ylim(ys.min(), ys.max())

ax.add_collection(line_segments)
ax.set_title('Line collection with masked arrays')
plt.show()

Map Colors to Values

We can also map an array of values to colors using the ScalarMappable.set_array function. We will create a new set of data and a new LineCollection object with the array parameter set to the x values. We can then use the colorbar method of the Figure object to add a colorbar to the plot.

N = 50
x = np.arange(N)
ys = [x + i for i in x]
segs = [np.column_stack([x, y]) for y in ys]

fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(ys), np.max(ys))

line_segments = LineCollection(segs, array=x,
                               linewidths=(0.5, 1, 1.5, 2),
                               linestyles='solid')
ax.add_collection(line_segments)
axcb = fig.colorbar(line_segments)
axcb.set_label('Line Number')
ax.set_title('Line Collection with mapped colors')
plt.sci(line_segments)
plt.show()

Summary

In this tutorial, we learned how to use the LineCollection function in Matplotlib to efficiently draw multiple lines at once. We saw how to plot multiple lines with different colors and styles, and how to use a masked array to mask some values. We also learned how to use the ScalarMappable.set_array function to map an array of values to colors.

Other Python Tutorials you may like