举例说明如何使用Matplotlib图例

96 阅读2分钟

在Matplotlib中,面向对象编程的核心思想是创建一个图形对象,然后调用该图形对象的方法和属性来绘制图像。在这个过程中,PyPlot库负责生成一个图形对象,并通过该对象添加一个或多个对象(即绘图区域)。本文将通过一些例子告诉你如何使用Matplotlib图形对象。

1.如何使用Matplotlib 图形对象来绘制图形

  1. Matplotlib提供了matplotlib.figure图形类模块,它包含了创建图形对象的方法。

  2. 你可以调用pythonPyPlot模块的figure()方法来创建图形对象实例。

  3. 下面是关于如何使用PyPlot模块的figure()方法来绘制图形的步骤。

  4. from matplotlib import pyplot as plt
    

    导入Matplotlib库中的pyplot模块。

  5. 调用PyPlot模块的figure()方法来创建一个空白画布。

    figure_object = plt.figure()
    
  6. figure()方法包含以下参数。

    dgecolor : Border color. 
    
    dpi : Specifies the resolution of the drawing object, that is, how many pixels per inch. The default value is 80.
    
    facecolor : Background color.
    
    figsize : Specifies the size of the canvas (width, height), in inches.
    
    frameon : Specify whether show the border or not.
    
  7. add_axes():在画布上添加轴的轴域。这个方法的参数值是一个序列。序列中的四个数字分别对应于图形的左边、下面、宽度和高度,每个数字必须在0和1之间。

    ax = figure_object.add_axes([0, 0, 1, 1])
    
  8. 设置图的标题为'cos波'。

    >>> ax.set_title("cos wave")
    Text(0.5, 1.0, 'cos wave')
    
  9. 设置图的x标签为'角度'。

    >>> ax.set_xlabel("angle")
    Text(0.5, 0, 'angle')
    
  10. 将图中的y标签设为'cos'。

```
>>> ax.set_ylabel("cos")
Text(0, 0.5, 'cos')
```

11. 调用plot(x, y)方法来绘制图形。

```
>>> ax.plot(x, y)
```

2.Matplotlib图形示例

  1. 下面是Matplotlib图形示例的源代码。

    # import the matplotlib pyplot module.
    from matplotlib import pyplot as plt
    
    # import the numpy module.
    import numpy as np
     
    # import the math module.
    import math
    
    # generate the x axis value.
    x = np.arange(0, math.pi*2, 0.05)
    
    # caculate the y axis value with the numpy cos() method.
    y = np.cos(x)
    
    # call the PyPlot module's figure() method to create the Matplotlib figure object.
    figure_object = plt.figure()
    
    # create a canvas object in the figure object.
    ax = figure_object.add_axes([0,0,1,1])
    
    # plot the green dot cos curve. 
    ax_plot = ax.plot(x,y, 'g.')
    
    print(ax_plot[0])
    
    # display the figure.
    plt.show()
    
  2. 当你运行上述例子的源代码时,你会得到下面的图。
    green-dot-cosine-curve