Skip to content Skip to sidebar Skip to footer

Having Line Color Vary With Data Index For Line Graph In Matplotlib?

So I have a 2D array of data producing a plot of many timeseries on the same axes. At the moment, the colour of each line just cycles through and doesn't mean anything. I want to

Solution 1:

Often you pass a colormap to a plotting function, but you can also pass a number or array to a colormap and get the colors in return.

So to color each line according to a variable, do something like this:

numlines = 20

for i in np.linspace(0,1, numlines):
    plt.plot(np.arange(numlines),np.tile([i],numlines), linewidth=4, color=plt.cm.RdYlBu(i))

enter image description here

Solution 2:

plot(x,y,'r') for red lines

plot(x,y,'b') for blue lines


Need more colors for a decent X'mas? See here.


UPDATES:

As you asked, there're too many lines to manually set colors. So how about this:

from matplotlib.pyplot import *

x = list(range(10))
amount = 20for i inrange(amount):
    y = [j-i for j in x]
    c = [float(i)/float(amount), 0.0, float(amount-i)/float(amount)] #R,G,B
    plot(x, y, color=c)
show()

It gives:

enter image description here

Solution 3:

Here I use rgb colors to get an array of 200 different colors. I don't have the time to sort them by intensity, but do a few printouts of the array and you might figure out how. An idea is to sort by the index of the sum of the (sorted) tuples.

#colorwheelimport matplotlib.pyplot as plt
from itertools import permutations
from random import sample
import numpy as np

#Get the color-wheel
Nlines = 200
color_lvl = 8
rgb = np.array(list(permutations(range(0,256,color_lvl),3)))/255.0
colors = sample(rgb,Nlines)


#Plots
x = np.linspace(0,2*np.pi)

for i inrange(Nlines):
    plt.plot(i*np.cos(x),i*np.sin(x),color=colors[i]) #color from index
plt.savefig("SO_colorwheel.png")
plt.show()

Gives enter image description here

Solution 4:

if someone is still looking for a way to color the curve along the path using some colormap, without using a scatter, I think the better way is to split it to segments and call colormap for the color

import matplotlib.pyplot as plt
import numpy as np

defplot_colored(x, y, c, cmap=plt.cm.jet, steps=10):
    c = np.asarray(c)
    c -= c.min()
    c /= c.max()
    it=0while it<с.size-steps:
        x_segm = x[it:it+steps+1]
        y_segm = y[it:it+steps+1]
        c_segm = cmap( c[it+steps//2] )
        plt.plot(x_segm, y_segm, c=c_segm)
        it += steps

# sample track
t = np.r_[0:10:1000j]
x = t**.25*np.sin(2*np.pi*t)
y = t**.25*np.cos(2*np.pi*t)

plt.figure()
plot_colored(x, y, t)

(smaller step makes it smoother but slower) example

Post a Comment for "Having Line Color Vary With Data Index For Line Graph In Matplotlib?"