【问题标题】:Conditional function plotting in matplotlibmatplotlib 中的条件函数绘图
【发布时间】:2016-05-26 23:15:16
【问题描述】:

我的目标是绘制一个具有两个变量 t 和 x 的函数。 如果 0,我们将 0 分配给 x

import matplotlib.pyplot as plt
import numpy as np
t=np.linspace(0,5,100)
def x(i):
    if i <= 1:
        j = 1
    else :
        j = 0
    return j
y = 8*x(t)-4*x(t/2)-3*x(t*8)

plt.plot(t,y)
plt.ylabel('y')
plt.xlabel('t')
plt.show()

它返回一个错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

    标签: python function matplotlib plot conditional


    【解决方案1】:

    您可以在分配y 时遍历t 中的值,因为您的函数x 只接受一个数字作为其参数。试试这个:

    y = np.array([8*x(tt)-4*x(tt/2)-3*x(tt*8) for tt in t])
    
    print y
    
    array([ 1,  1,  1,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
            4,  4,  4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
           -4, -4, -4, -4, -4, -4,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
            0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0])
    

    不过,矢量化答案(例如 @Christoph 和 @xnx)是一种更好的方法

    【讨论】:

      【解决方案2】:

      您不能在 numpy 数组上使用经典的 if,至少不能在逐点意义上使用。这不是问题,因为您可以对数组进行布尔运算:

      def x(i):
          j = (i<=1)*1.
          return j
      

      【讨论】:

        【解决方案3】:

        您的函数x 无法按原样处理数组输入(因为比较操作)。您可以在此函数中创建一个临时数组来设置适当的值:

        def x(t):
            tmp = np.zeros_like(t)    
            tmp[t <= 1] = 1
            return tmp
        

        【讨论】:

          【解决方案4】:

          你想用那个代码做什么?看看t 是一个 np.array 然后你将它用作单个数字元素明智的运算符在这种情况下不起作用也许你更喜欢使用像这样的循环:

          import matplotlib.pyplot as plt
          import numpy as np
          t=np.linspace(0,5,100)
          def x(i):
              if i <= 1:
                  j = 1
              else :
                  j = 0
              return j
          y = []
          for i in t:
              y.append(8*x(i)-4*x(i/2)-3*x(i*8))
          
          # or using list comprehensions
          y = [8*x(i)-4*x(i/2)-3*x(i*8) for i in t]
          
          plt.plot(t,y)
          plt.ylabel('y')
          plt.xlabel('t')
          plt.show()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-27
            • 2018-12-29
            • 2013-04-06
            • 2020-02-28
            • 1970-01-01
            相关资源
            最近更新 更多