Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib plotting a single line that continuously changes color

Tags:

matplotlib

I would like to plot a curve in the (x,y) plane, where the color of the curve depends on a value of another variable T. x is a 1D numpy array, y is a 1D numpy array.

T=np.linspace(0,1,np.size(x))**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)

I want the line to change from blue to red (using RdBu colormap) depending on the value of T (one value of T exists for every (x,y) pair).

I found this, but I don't know how to warp it to my simple example. How would I use the linecollection for my example? http://matplotlib.org/examples/pylab_examples/multicolored_line.html

Thanks.

like image 858
Cokes Avatar asked Apr 17 '13 04:04

Cokes


Video Answer


1 Answers

One idea could be to set the color using color=(R,G,B) then split your plot into n segments and continuously vary either one of the R, G or B (or a combinations)

import pylab as plt
import numpy as np

# Make some data
n=1000
x=np.linspace(0,100,n)
y=np.sin(x)

# Your coloring array
T=np.linspace(0,1,np.size(x))**2
fig = plt.figure()
ax = fig.add_subplot(111)

# Segment plot and color depending on T
s = 10 # Segment length
for i in range(0,n-s,s):
    ax.plot(x[i:i+s+1],y[i:i+s+1],color=(0.0,0.5,T[i]))

Hope this is helpful

like image 174
Greg Avatar answered Sep 19 '22 07:09

Greg