Home >Backend Development >Python Tutorial >How to Plot a Line with Varying Colors Using Matplotlib?

How to Plot a Line with Varying Colors Using Matplotlib?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 06:51:30504browse

How to Plot a Line with Varying Colors Using Matplotlib?

Plotting a Line with Varying Colors

Problem

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.

Solution

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!

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