Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a multicolored curve using a single plot command in matplotlib

If I understand correctly, the function:

matplotlib.pyplot.plot(x, y)

plots len(x)-1 separate line segments - one going from (x[0], y[0]) to (x[1],y[1]), one going from (x[1],y[1]) to (x[2], y[2]), etc. In my application, I want to display a curve consisting of a series of line segments connecting data points in this way, but there is an extra piece of data (z) associated with the transition between each of these data points, that I want to represent by the color of the line segment. Clearly one way of doing this is the following:

for i in range(len(x)-1)):
    matplotlib.pyplot.plot(x[i:i+2],y[i:i+2], color=z[i])

but is there a way to do it that doesn't involve a separate call to matplotlib.pyplot.plot for each line segment?

like image 362
Alex319 Avatar asked Apr 11 '26 01:04

Alex319


1 Answers

You should be able to use matplotlib.collections.LineCollection which accepts a colors parameter (sequence of RGBA tuples).

like image 131
Andrew Clark Avatar answered Apr 13 '26 15:04

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!