zoukankan      html  css  js  c++  java
  • 使用matplotlib.pyplot中的三种方法画子图

    本文所用包:

    from matplotlib import pyplot as plt

    import numpy as np

    此文主要记录使用matplotlib.pyplot中的三个函数,主要结合代码展示效果:

    一、plt.subplots

    实例代码:

     1 from matplotlib import pyplot as plt
     2 import numpy as np
     3 
     4 x = np.linspace(1, 100, num= 25, endpoint = True)
     5 
     6 def y_subplot(x,i):
     7     return np.cos(i * np.pi *x)
     8 
     9 #使用subplots 画图
    10 f, ax = plt.subplots(2,2)
    11 #type(f) #matplotlib.figure.Figure
    12 
    13 style_list = ["g+-", "r*-", "b.-", "yo-"]
    14 ax[0][0].plot(x, y_subplot(x, 1), style_list[0])
    15 ax[0][1].plot(x, y_subplot(x, 2), style_list[1])
    16 ax[1][0].plot(x, y_subplot(x, 3), style_list[2])
    17 ax[1][1].plot(x, y_subplot(x, 4), style_list[3])
    18 
    19 plt.show()

    注释:使用subplots会返回两个东西,一个是matplotlib.figure.Figure,也就是f,另一个是Axes object or array of Axes objects,也就是代码中的ax;

    把f理解为你的大图,把ax理解为包含很多小图对象的array;所以下面的代码就使用ax[0][0]这种从ax中取出实际要画图的小图对象;画出的图如下所示;

    二、plt.subplot;

    实例代码:

    #使用subplot画图
    for i in  range(1,5):
        plt.subplot(2,2,i)
        plt.plot(x, y_subplot(x,i), style_list[i- 1])
    plt.show()

    plt.subplot函数的第一个参数和第二个参数分别制定了子图有几列和几行;这个和subplots的参数意思相同;第三个参数就是指定在那个子图上画图的顺序,分别是从左往右;慢慢体味subplot和subplots的区别吧;subplot方法画的图如下所示:

     

    三、plt.add_subplots

    实例代码:

    fig = plt.figure()
    for i in range(1,5):
        ax = fig.add_subplot(2,2,i)
        ax.plot(x, y_subplot(x,i), style_list[i -1])
    
    plt.show()

    add_subplot函数也就是向Figure画板中添加每一个子图

    画出的图形如下所示:

  • 相关阅读:
    jquery ajax 后台响应成功,返回正确json但不执行success方法,执行error的问题
    bootstrap轮播组件,大屏幕图片居中效果
    mouseover和mouseout事件在鼠标经过子元素时也会触发
    vertical-align的深入学习
    小技巧
    css字体大小设置em与rem的区别
    子元素的margin-top影响父元素原因和解决办法
    JavaScript随机打乱数组
    JavaScript 获取当月天数
    javaScript 的option触发事件
  • 原文地址:https://www.cnblogs.com/nobbyoucanyouup/p/9239943.html
Copyright © 2011-2022 走看看