如何更改绘图,以使每个图形具有不同的颜色?

时间:2019-05-02 21:58:39

标签: 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([])
    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() 

2 个答案:

答案 0 :(得分:2)

您只需要在for循环外进行ax.plot调用,并绘制不带P的{​​{1}},而不必用'r'标志强制显示红色,就像

n

在原始代码中,您分别绘制每个点。 这是不必要的,因为matplotlib可以直接绘制矢量或与此相关的列表。 因此,您可以简单地填充for n in range(N+1): Pn = P[n] + h*f(P[n]) P = np.append(P,Pn) ax.plot(P, 'o') ,然后在没有X数据的情况下进行绘制。

P选项的意思是:

  • 绘制红色标记('ro'
  • 使用圆形标记(r

如果您删除颜色选项并仅传递o,则matplotlib将负责以不同的颜色绘制每个函数。

答案 1 :(得分:1)

尽管@right腿已经指出了问题,但您可能会对了解如何获取图例感兴趣。

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