Home > Backend Development > Python Tutorial > How to Plot Colored Line Segments in Matplotlib?

How to Plot Colored Line Segments in Matplotlib?

Mary-Kate Olsen
Release: 2024-10-29 07:39:02
Original
694 people have browsed it

How to Plot Colored Line Segments in Matplotlib?

Colored Line Segments in Matplotlib

Plotting lines with distinct colors can be achieved through various methods. The preferred approach depends on the number of line segments to be rendered.

Small Number of Line Segments

For a small number of line segments (e.g., less than 10), the following approach suffices:

<code class="python">import numpy as np
import matplotlib.pyplot as plt

# Define line segment data
xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0)

# Create figure and axes
fig, ax = plt.subplots()

# Iterate through line segments
for start, stop in zip(xy[:-1], xy[1:]):
    x, y = zip(start, stop)
    ax.plot(x, y, color=np.random.rand(3))

plt.show()</code>
Copy after login

Large Number of Line Segments

For a large number of line segments (e.g., over a thousand), LineCollections provide a more efficient solution:

<code class="python">import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# Define line segment data
xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)

# Reshape data into segments
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])

# Create figure and axes
fig, ax = plt.subplots()

# Create LineCollection with random colors
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)
coll.set_array(np.random.random(xy.shape[0]))

# Add LineCollection to axes
ax.add_collection(coll)
ax.autoscale_view()

plt.show()</code>
Copy after login

Color Selection

Both methods rely on random color selection from the "gist_ncar" coloramp. For a larger selection, refer to: http://matplotlib.org/examples/color/colormaps_reference.html

The above is the detailed content of How to Plot Colored Line Segments in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template