1

I'm confused about how I can change the colors of graphs in the plots, each line represents an approximation of Euler with different h value.

import numpy as np
import matplotlib.pylab as plt

# your function
def Eulergraph(h, N, ax):
    K = 12; r = 0.43; Po = 1;

#defining dP/dt as a function f(P)
    f = lambda P: r*P*(1-P/K)

    P = np.array([])
    P = np.append(P,Po) #initializing P with Po

    for n in range(N+1):
        Pn = P[n] + h*f(P[n])
        P = np.append(P,Pn)





# formatting of your plot
plt.xlabel (' Value of n ”' )
plt.ylabel (" Value of p[n] ”")
plt.title (" Approximate Solution with Euler’s Method " )
plt.show() 
0

2 Answers 2

2

You just have to take the ax.plot call outside of the for loop, and just plot P without n, without forcing a red color with the 'r' flag, just like that:

for n in range(N+1):
    Pn = P[n] + h*f(P[n])
    P = np.append(P,Pn)

ax.plot(P, 'o')

In your original code, you plot each point independently. This is not necessary, as matplotlib can directly plot a vector, or a list for that matter. So you can simply populate P, and then plot it without X data.

The 'ro' options mean:

  • Draw red markers (r)
  • Use round markers (o)

If you remove the color option and simply pass o, matplotlib will take care of drawing each function in a distinct color.

Sign up to request clarification or add additional context in comments.

Comments

1

While @Right leg already pointed out the problem, you might be interested in knowing how to get legends.

import numpy as np
import matplotlib.pylab as plt

# your function
def Eulergraph(h, N, ax):
    K = 12; r = 0.43; Po = 1;
    f = lambda P: r*P*(1-P/K)
    P = np.array([Po]) # Modified this line

    for n in range(N+1):
        Pn = P[n] + h*f(P[n])
        P = np.append(P,Pn)
    ax.plot (P, '-', label='h=%s' %h) # Added legend here

# create your figure and axis object
fig = plt.figure()
ax = plt.gca()

# pass the axis object as a parameter
Eulergraph(1,30,ax)       
Eulergraph(.5,30,ax)   
Eulergraph(.1,30,ax)

# formatting of your plot
plt.xlabel (' Value of n ”' )
plt.ylabel (" Value of p[n] ”")
plt.title (" Approximate Solution with Euler’s Method " )
plt.legend() # Show the legend 
plt.show() 

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.