Python 如何更改绘图,使每个图形具有不同的颜色?
我对如何改变图中图形的颜色感到困惑,每一条线代表一个具有不同h值的欧拉近似值Python 如何更改绘图,使每个图形具有不同的颜色?,python,matplotlib,Python,Matplotlib,我对如何改变图中图形的颜色感到困惑,每一条线代表一个具有不同h值的欧拉近似值 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([])
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()
您只需在for循环之外调用
ax.plot
,只需在不使用n
的情况下绘制p
,而不使用带有“r”标志的红色,就像这样:
for n in range(N+1):
Pn = P[n] + h*f(P[n])
P = np.append(P,Pn)
ax.plot(P, 'o')
在原始代码中,可以独立绘制每个点。
这是不必要的,因为matplotlib可以直接绘制向量或列表。
因此,您可以简单地填充P
,然后在没有X数据的情况下绘制它
'ro'
选项表示:
- 绘制红色标记(
)r
- 使用圆形标记(
)o
如果删除颜色选项,只需传递
o
,matplotlib将负责以不同的颜色绘制每个函数。虽然@Right leg已经指出了问题,但您可能有兴趣了解如何获取图例
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()
下面的任何答案都能解决您的问题吗?如果他们这样做了,那么就把你认为最好的答案标记为被接受。由于您似乎不熟悉堆栈溢出,因此应该阅读