"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Plot Lines with Varying Colors in Matplotlib?

How to Plot Lines with Varying Colors in Matplotlib?

Published on 2024-11-08
Browse:828

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:

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()

Large Number of Line Segments

When handling a vast number of line segments, a more efficient method is utilizing a LineCollection.

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()

In both methods, the selected colormap can be changed by referring to the Matplotlib documentation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3