Caterina
Caterina

Reputation: 987

How to change line colors succesively in a graph using matplotlib

so I have this lines being plotted

x=0.2  
r_1=3
n=1000

for i in range (n):
        x_n1=r_1*x*(1 -x)
        plt.plot([x, x], [x, x_n1], color='green')
        plt.plot([x, x_n1], [x_n1, x_n1], color='green')
        x=x_n1
plt.show()

they're all green. How can I make each of them change its color (as in the rainbow order of colors) in each iteration? What I want to achieve is something like this cobweb map

Upvotes: 0

Views: 322

Answers (1)

Sebastian Mendez
Sebastian Mendez

Reputation: 2981

color accepts multiple types of inputs, such as a tuple of RGB values. However, the best method to create a rainbow would be with HSV. Fortunately, matplotlib.colors has a hsv_to_rgb function:

import matplotlib.colors as colors
color = .5 #Value between 0 and 1, 0 and 1 being red
print(colors.hsv_to_rgb((color, 1, 1)) #[ 0.  1.  1.]

Now, we just want to shift through all values as we iterate from 0 to n-1:

for i in range (n):
    color=colors.hsv_to_rgb((i/n, 1, 1))
    x_n1=r_1*x*(1 -x)
    plt.plot([x, x], [x, x_n1], color=color)
    plt.plot([x, x_n1], [x_n1, x_n1], color=color)
    x=x_n1
plt.show()

You'll notice that almost all of lines are reddish. This is due to most of the prevalent lines being the first 50, which are all very close to red. You can adapt this as you see fit; one such option would be to have color=colors.hsv_to_rgb(((i/n)**(1/2), 1, 1)).

Upvotes: 1

Related Questions