Home >Backend Development >Python Tutorial >How to Plot a Line with Varying Colors Using Matplotlib?
Given two lists of data points, latt and lont, the goal is to visualize the data as a line with varying colors. The line should be segmented into periods, with each period comprising 10 data points from both lists. Different colors should be assigned to each period.
Method 1: Limited Number of Line Segments
For a small number of line segments, the following approach can be used:
<code class="python">import numpy as np import matplotlib.pyplot as plt def uniqueish_color(): """Generate a unique-looking color.""" return plt.cm.gist_ncar(np.random.random()) # Generate random data xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0) # Create a figure and axis fig, ax = plt.subplots() # Iterate over segments for start, stop in zip(xy[:-1], xy[1:]): x, y = zip(start, stop) ax.plot(x, y, color=uniqueish_color()) # Display the plot plt.show()</code>
Method 2: Large Number of Line Segments
For a large number of line segments, a LineCollection can be used to improve performance:
<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 xy = xy.reshape(-1, 1, 2) segments = np.hstack([xy[:-1], xy[1:]]) # Create a figure and axis fig, ax = plt.subplots() # Create a LineCollection coll = LineCollection(segments, cmap=plt.cm.gist_ncar) # Set colors coll.set_array(np.random.random(xy.shape[0])) # Add collection to axis ax.add_collection(coll) # Adjust view ax.autoscale_view() # Display the plot plt.show()</code>
The above is the detailed content of How to Plot a Line with Varying Colors Using Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!