To state it in a general form, I'm looking for a way to join several points with a gradient color line using matplotlib, and I'm not finding it anywhere. To be more specific, I'm plotting a 2D random walk with a one color line. But, as the points have a relevant sequence, I would like to look at the plot and see where the data has moved. A gradient colored line would do the trick. Or a line with gradually changing transparency.
I'm just trying to improve the vizualization of my data. Check out this beautiful image produced by the ggplot2 package of R. I'm looking for the same in matplotlib. Thanks.
I was using @alexbw code, for plotting a parabola. It works very well. I am I able to change set of colors for the function. For computation, it took me around 1min and 30sec. I was using Intel i5, graphics 2gb, 8gb ram.
The code is following:
And the result is: https://i.stack.imgur.com/gL9DG.png
I recently answered a question with a similar request ( creating over 20 unique legend colors using matplotlib ). There I showed that you can map the cycle of colors you need to plot your lines to a color map. You can use the same procedure to get a specific color for each pair of points.
You should choose the color map carefully, because color transitions along your line might appear drastic if the color map is colorful.
Alternatively, you can change the alpha of each line segment, ranging from 0 to 1.
Included in the code example below is a routine (
highResPoints
) to expand the number of points your random walk has, because if you have too few points, the transitions may seem drastic. This bit of code was inspired by another recent answer I provided: https://stackoverflow.com/a/8253729/717357This figure shows the four cases:
Note that if you have many points, calling
plt.plot
for each line segment can be quite slow. It's more efficient to use a LineCollection object.Using the
colorline
recipe you could do the following:I've added my solution using pcolormesh Every line segment is drawn using a rectangle which is interpolating between colors at each end. So it truly is interpolating the color, but we have to pass a thickness of the line.
Too long for a comment, so just wanted to confirm that
LineCollection
is a great deal faster than a for-loop over line subsegments.the LineCollection method is a great deal faster in my hands.
We'll test iterative plotting against LineCollection method above.
1 loops, best of 1: 13.4 s per loop
1 loops, best of 1: 532 ms per loop
Upsampling your line for a better color gradient, as the currently selected answer provides, is still a good idea if you want a smooth gradient and you only have a few points.