【问题标题】:Plot Piecewise Function in Python在 Python 中绘制分段函数
【发布时间】:2015-10-16 18:39:59
【问题描述】:

我想使用 Matplotlib 在 Python 中绘制以下分段函数,从 0 到 5。

f(x) = 1, x != 2; f(x) = 0, x = 2

在 Python 中...

def f(x):
 if(x == 2): return 0
 else: return 1

使用 NumPy 创建一个数组

x = np.arange(0., 5., 0.2)

    array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8,  2. ,
        2.2,  2.4,  2.6,  2.8,  3. ,  3.2,  3.4,  3.6,  3.8,  4. ,  4.2,
        4.4,  4.6,  4.8])

我尝试过...

import matplotlib.pyplot as plt
plt.plot(x,f(x))

或者……

vecfunc = np.vectorize(f)
result = vecfunc(t)

或者……

def piecewise(x):
 if x == 2: return 0
 else: return 1

import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
plt.plot(x, map(piecewise, x))

ValueError: x and y must have same first dimension

但我没有正确使用这些功能,现在只是随机猜测如何做到这一点。

一些答案​​开始出现......但是这些点被连接成情节上的一条线。我们如何绘制点?

【问题讨论】:

    标签: python python-3.x numpy matplotlib


    【解决方案1】:

    问题在于函数f 不将数组作为输入,而是将单个数字作为输入。你可以:

    plt.plot(x, map(f, x))
    

    map 函数接受函数 f、数组 x 并返回另一个数组,其中函数 f 应用于数组的每个元素。

    【讨论】:

    • 将使用我使用的代码更新我的帖子,但我得到了,ValueError: x and y must have same first dimension
    • plt.plot 需要一个数组或列表,而不是生成器(这是map 返回的),使用:plt.plot(x, list(map(piecewise, x)))
    • 现在绘图...但是这些点被一条线连接...如何绘制点?
    • @DanCiborowski-MSFT 您可以使用plt.scatter 而不是plt.plot 以仅绘制点
    【解决方案2】:

    你可以在数组上使用np.piecewise

    x = np.arange(0., 5., 0.2)
    import matplotlib.pyplot as plt
    plt.plot(x, np.piecewise(x, [x  == 2, x != 2], [0, 1]))
    

    【讨论】:

    • 试图用这种方法来视觉解决一个极限问题。看看这张图表,你会认为极限是 0... 并且缩小 0.2 会导致垂直线 a x=2... 无论如何不要连接线的点?
    • @DanCiborowski-MSFT,你可以选择你想要的任何类型的图,如果你想要散点图然后使用散点图
    • 这给了我错误 []
    【解决方案3】:

    一些答案​​开始出现......但要点正在 在情节上连接成一条线。我们如何绘制点?

    import matplotlib.pyplot as plt
    import numpy as np
    
    def f(x):
     if(x == 2): return 0
     else: return 1
    
    x = np.arange(0., 5., 0.2)
    
    y = []
    for i in range(len(x)):
       y.append(f(x[i]))
    
    print x
    print y
    
    plt.plot(x,y,c='red', ls='', ms=5, marker='.')
    ax = plt.gca()
    ax.set_ylim([-1, 2])
    
    plt.show()
    

    【讨论】:

      【解决方案4】:

      追加有效,但需要一些额外的处理。 np 的分段工作正常。可以对任何功能执行此操作:

      `

      import math
      import matplotlib as plt
      
      xs=[]
      xs=[x/10 for x in range(-50,50)]   #counts in tenths from -5 to 5
      
      plt.plot(xs,[f(x) for x in xs])
      

      `

      【讨论】:

        【解决方案5】:

        如果您使用的是 python 2.x,map() 会返回一个列表。 所以你可以这样写代码:

        import matplotlib.pyplot as plt
        import numpy as np
        
        
        def f(t):
            if t < 10:
                return 0;
            else:
                return t * t - 100;
        
        
        t = np.arange(0, 50, 1)
        
        plt.plot(t, map(f, t), 'b-')
        
        plt.show()
        

        如果您使用的是 python 3.x,map() 返回一个迭代器。 所以将地图转换为列表。

        plt.plot(t, list(map(f, t)), 'b-')
        

        【讨论】:

          【解决方案6】:

          您的函数是连续的,除了零度量的间隔。在我看来,绘制它的正确方法是

          In [8]: import matplotlib.pyplot as plt
             ...: plt.plot((0, 5), (1, 1), color='blue', label='Discontinuos function')
             ...: plt.scatter(2, 0, color='blue')
             ...: plt.grid()
             ...: plt.legend()
             ...: plt.show()
          
          In [9]: 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-21
            • 2015-08-02
            • 1970-01-01
            相关资源
            最近更新 更多