Reputation: 1577
I am trying to run a for loop that cycles through colours for each iteration of a for loop. I am finding similar questions that cycle through colours but not one that is dependent on a particular for loop. I provide some links below:
How to pick a new color for each plotted line within a figure in matplotlib?
My code is for a simple random walk
# Parameters
ntraj=10
n=20
p=0.4
# Initialize holder for trajectories
xtraj=np.zeros(n+1,float)
# Simulation
for j in range(ntraj):
for i in range(n):
xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
plt.plot(range(n+1),xtraj,'b-',alpha=0.2)
plt.title("Simple Random Walk")
I would like to create a line with a different colour for each j
. I apologize if the answer is obvious. I am a novice at python.
Upvotes: 1
Views: 15731
Reputation: 13349
Choose any colour palette you like from matplotlib.cm
Try:
# Parameters
ntraj=10
n=20
p=0.4
colors = plt.cm.jet(np.linspace(0,1,ntraj))# Initialize holder for trajectories
xtraj=np.zeros(n+1,float)
# Simulation
for j in range(ntraj):
for i in range(n):
xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
plt.plot(range(n+1),xtraj,'b-',alpha=0.2, color=colors[j])
plt.title("Simple Random Walk")
Upvotes: 5
Reputation: 105
You have several options using matplotlib.pylplot.
Besides the already provided solutions, you can define your color directly and change the values depending on your for loop:
# Parameters
ntraj=10
n=20
p=0.4
xtraj=np.zeros(n+1,float)
# Simulation
for j in range(ntraj):
for i in range(n):
xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
ctemp = 0.1+(j-1)/ntraj
plt.plot(range(n+1),xtraj,'b-',alpha=0.2, color=(ctemp, ctemp, ctemp))
plt.title("Simple Random Walk")
Upvotes: 3
Reputation: 661
I added a list of colors. I'm pretty sure they can be RGB or Hex. Then inside the j loop the color will switch to the next index.
colors = ['b','g','r','c','m','y']
# Parameters
# Simulation
for j in range(ntraj):
color = colors[j % len(colors)]
for i in range(n):
xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
plt.plot(range(n+1),xtraj,"{}-".format(color),alpha=0.2)
plt.title("Simple Random Walk")
Upvotes: 6
Reputation: 448
As it is now, new colour will be taken for each line. If you want to limit choices and loop through a list you can use itertools.cycle
:
from itertools import cycle
colours = cycle(['red', 'green', 'blue'])
# Simulation
for j in range(ntraj):
for i in range(n):
xtraj[i+1]=xtraj[i]+2.0*np.random.binomial(1,p)-1.0
plt.plot(range(n+1),xtraj,'b-',alpha=0.2, color=colours.next())
Upvotes: 6