Home > Article > Backend Development > How to Plot 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.
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>
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>
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!