Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i put a color changer in a loop?

So basically what i'm wondering, is at the bottom of my code when i plot the graph of my trials, is there a way to run a color generator through there? Or more explicitly put, could i make a list of warm colors, and put that into my plot function, where it runs through each color in a list as the loop runs through, and therefore my plot would only consist of warm colors?

from numpy import *
from pylab import show,plot
from scipy.special import erfinv    
n = 366 #number of days     
ntrials = 5000
u = random.rand(ntrials)
v = sqrt(2.)*erfinv(2.*u-1.)
mu = 0                                          
sigma = .05                             
investment = 1000.              
data = empty((ntrials,n))
data[:,0] = investment        
for t in range(n-1):
    u = random.rand(ntrials)
    v = sqrt(2.)*erfinv(2.*u-1.)
    epsilon = v
    data[:,t+1] = (1. + mu +sigma*epsilon)*data[:,t]

data2 = data.sum(axis=0)
woo = data2[-1]/ntrials                 
data3 = data2[-1]
x = linspace(0,n,n)
for t in range(n):
    plot(x,data[t,:])    
show()
like image 400
KevinShaffer Avatar asked Apr 03 '12 18:04

KevinShaffer


1 Answers

It sounds like you just want something like this?

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Generate data...
nx, nsteps = 100, 20
x = np.linspace(0, 1, nx)
data = np.random.random((nx, nsteps)) - 0.5
data = data.cumsum(axis=0)
data = data.cumsum(axis=1)

# Plot
cmap = mpl.cm.autumn
for i, y in enumerate(data.T):
    plt.plot(x, y, color=cmap(i / float(nsteps)))

plt.show()

enter image description here

The key is that calling a matplotlib colormap instance with a value between 0 and 1 will return a color (where 0 is the lowest color in the colormap and 1 is the highest).

For a list of available colormaps, see here. You can access the reversed version of any of these with name_r (e.g. the reversed version of mpl.cm.autumn is mpl.cm.autumn_r).

like image 92
Joe Kington Avatar answered Sep 22 '22 20:09

Joe Kington