【问题标题】:How can I change my plot so that each graph is a different color?我怎样才能改变我的情节,使每张图都是不同的颜色?
【发布时间】:2019-05-03 09:38:25
【问题描述】:

我对如何更改图中图形的颜色感到困惑,每条线代表具有不同 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() 

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您只需要在 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 将负责以不同的颜色绘制每个函数。

【讨论】:

    【解决方案2】:

    虽然@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() 
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2021-11-07
      • 2017-12-29
      • 2014-05-14
      相关资源
      最近更新 更多