Home > Backend Development > Python Tutorial > How to Plot Lines with Varying Colors in Matplotlib?

How to Plot Lines with Varying Colors in Matplotlib?

Patricia Arquette
Release: 2024-10-29 08:58:02
Original
894 people have browsed it

How to Plot Lines with Varying Colors in Matplotlib?

Plotting Lines with Varying Colors

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.

Small Number of Line Segments

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>
Copy after login

Large Number of Line Segments

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>
Copy after login

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template