Skip to content
Advertisement

How to plot a gradient color line in matplotlib?

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.

enter image description here

Advertisement

Answer

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/717357

JavaScript

This figure shows the four cases:

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement