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

How to Plot Colored Line Segments in Matplotlib?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 07:39:02655browse

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>

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>

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!

Statement:
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