如何使用PyLab绘制曲线

165 阅读1分钟

PyLabMatplotlib的一个绘图库接口,其语法与MATLAB非常相似。它可以和PyPlot模块一起使用,实现Matplotlib的绘图功能。PyLab是一个独立的模块,与Matplotlib包一起安装。

1.如何导入PyLab和PyPlot。

  1. 首先,确保你已经安装了Python Matplotlib库,请阅读文章《如何在Windows、Mac和Linux上安装Python包Numpy、Pandas、Scipy、Matplotlib》。

  2. 然后你可以使用下面的python源代码来导入PyLabPyPlot模块。

    # below code can import the Pyplot library.
    from matplotlib import pytplot as plt
    # you can use the below 2 way to import the PyLab library.
    import pylab
    # import all the sub classes in the pylab module.
    from pylab import *
    

2.使用PyLab绘图功能绘制曲线的例子。

2.1 绘制二次曲线。

  1. 下面是Python的源代码。

    >>> from pylab import * # import all the methods from the pylab library. 
    >>>
    >>> x = linspace(-3, 3, 30) # calculate the x axis values.
    >>>
    >>> y = x**2 # the y axis value is x**2
    >>>
    >>> plot(x, y) # draw the quadratic curve.
    [<matplotlib.lines.Line2D object at 0x000001E1C4A26A60>]
    >>> show() # show the curve picture.
    
  2. 下面是二次曲线图。
    quadratic-curve

2.2 绘制红点二次方曲线。

  1. 下面是python的源代码。

    >>> from pylab import * # import the pylab library.
    >>>
    >>> x = linspace(-3, 3, 30) # calculate the x axis values
    >>>
    >>> y = x**2 # the y axis value is x**2
    >>>
    >>> plot(x, y, 'r.')  # r means red and . means dot line.
    [<matplotlib.lines.Line2D object at 0x000001E1C9AFC220>]
    >>> show()
    
  2. 下面是示例图。
    quadratic-curve-red-dot

2.3 绘制多条曲线。

  1. 下面是例子的源代码。

    >>> from pylab import * # import the  pylab module.
    >>>
    >>> plot(x, cos(x), 'b.') # plot a blue cos curve use the dot line.
    [<matplotlib.lines.Line2D object at 0x000001E1CE4392B0>]
    >>>
    >>> plot(x, -sin(x), 'r--') # plot a red -sin curve use two short line.
    [<matplotlib.lines.Line2D object at 0x000001E1CE439730>]
    >>>
    >>> plot(x, sin(x), 'g-') # plot a green sin curve use single short line.
    [<matplotlib.lines.Line2D object at 0x000001E1CE439AF0>]
    >>>
    >>> show() # show the multiple curve graph.
    
  2. 下面是上述例子生成的图形。
    sin-cos--sin-color-curve

The postHow To Draw A Curve Using PyLabappeared first on.