In matplotlib, plotting a line with distinct color segments can be achieved through several approaches. The choice depends on the number of line segments to be plotted.
If only a few line segments are required, as in plotting a trajectory, consider the following:
<code class="python">import numpy as np import matplotlib.pyplot as plt # Generate random data xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0) fig, ax = plt.subplots() # Plot each line segment with a unique color for start, stop in zip(xy[:-1], xy[1:]): x, y = zip(start, stop) ax.plot(x, y, color=plt.cm.gist_ncar(np.random.random())) plt.show()</code>
When handling a vast number of line segments, a more efficient method is utilizing a LineCollection.
<code class="python">import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection # Generate random data xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0) # Reshape data for compatibility with LineCollection xy = xy.reshape(-1, 1, 2) segments = np.hstack([xy[:-1], xy[1:]]) fig, ax = plt.subplots() # Create a LineCollection with randomly assigned colors coll = LineCollection(segments, cmap=plt.cm.gist_ncar) coll.set_array(np.random.random(xy.shape[0])) # Add the LineCollection to the plot ax.add_collection(coll) ax.autoscale_view() plt.show()</code>
In both methods, the selected colormap can be changed by referring to the Matplotlib documentation.
The above is the detailed content of How to Plot Lines with Varying Colors in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!