简体   繁体   中英

How to cycle through colors in a plot for each iteration of a for loop

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?

matplotlib.cycler

Color cycler demo

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.

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())

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")  

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")

在此处输入图像描述

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM