0
0
Matplotlibdata~5 mins

LineCollection and PolyCollection for speed in Matplotlib

Choose your learning style9 modes available
Introduction

LineCollection and PolyCollection help draw many lines or shapes fast. They make plots quicker when you have lots of data.

You want to draw many lines on a plot without slowing down.
You need to show many polygons or shapes quickly.
You want to improve plot speed when drawing complex figures.
You have a big dataset with many line segments or polygons.
You want to reduce the time it takes to update plots in animations.
Syntax
Matplotlib
from matplotlib.collections import LineCollection, PolyCollection

# Create a LineCollection
lines = LineCollection(list_of_lines, **kwargs)

# Create a PolyCollection
polys = PolyCollection(list_of_polygons, **kwargs)

# Add to axes
ax.add_collection(lines)
ax.add_collection(polys)

list_of_lines is a list of lines, each line is a list of (x, y) points.

list_of_polygons is a list of polygons, each polygon is a list of (x, y) points.

Examples
Create two red lines crossing each other with thickness 2.
Matplotlib
from matplotlib.collections import LineCollection
lines = [ [(0, 0), (1, 1)], [(1, 0), (0, 1)] ]
lc = LineCollection(lines, colors='red', linewidths=2)
Create two colored triangles with black edges.
Matplotlib
from matplotlib.collections import PolyCollection
polys = [ [(0, 0), (1, 0), (0.5, 1)], [(1, 1), (2, 1), (1.5, 2)] ]
pc = PolyCollection(polys, facecolors=['blue', 'green'], edgecolors='black')
Sample Program

This code draws three purple lines and two colored polygons quickly using collections. It shows how to add them to the plot and set limits.

Matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection, PolyCollection

fig, ax = plt.subplots()

# Define multiple lines
lines = [ [(0, 0), (1, 1)], [(1, 0), (0, 1)], [(0, 0.5), (1, 0.5)] ]
line_collection = LineCollection(lines, colors='purple', linewidths=2)
ax.add_collection(line_collection)

# Define multiple polygons
polygons = [ [(2, 0), (3, 0), (2.5, 1)], [(3, 1), (4, 1), (3.5, 2)] ]
poly_collection = PolyCollection(polygons, facecolors=['orange', 'cyan'], edgecolors='black', alpha=0.6)
ax.add_collection(poly_collection)

ax.set_xlim(-0.5, 4.5)
ax.set_ylim(-0.5, 2.5)
ax.set_aspect('equal')
plt.title('LineCollection and PolyCollection Example')
plt.show()
OutputSuccess
Important Notes

LineCollection and PolyCollection are faster than plotting lines or polygons one by one.

You can style all lines or polygons together using collections.

Remember to add the collection to the axes with ax.add_collection().

Summary

Use LineCollection to draw many lines fast.

Use PolyCollection to draw many polygons fast.

Collections improve plot speed and style consistency.