学习python库matplotlib之figure常见参数和subplot绘制子图(2)

1 matplotlib的figure常用参数及subplot子图

1.1 matplotlib之颜色、标记和线型

绘图中用到的直线属性包括:

  • (1)LineStyle:线形
  • (2)LineWidth:线宽
  • (3)Color:颜色
  • (4)Marker:标记点的形状
  • (5)label:用于图例的标签

注意:可以通过**help(plt.plot)**查看该API的参数设置情况

%matplotlib inline  
def sin():
    """
    绘制正余弦曲线
    """
    import numpy as np
    import matplotlib.pyplot as plt
    x = np.arange(-3,3,0.1)
    y1 = np.sin(x)
    
    # 绘制图像
    plt.figure()
    # alpha  透明度
    plt.plot(x,y1,color='red',linestyle="dashed",marker='o',markersize=10,alpha=0.5)
    
    plt.show()
sin()

学习python库matplotlib之figure常见参数和subplot绘制子图(2)_第1张图片

1.2 matplotlib之刻度、标题、标签和图例

  • legend ():
    生成默认图例, matplotlib 中的 legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构.

  • xlabel、ylabel:设置X轴Y轴标签

  • title:设置标题

  • xlim、ylim:控制图标的范围

  • xticks、yticks: 控制图标的刻度

  • gca获取当前坐标轴信息。使用spines设置边框,使用set_color设置边框颜色:默认白色

  • savefit(文件名称及路径) 保存图片

%matplotlib inline 
def eg_matplotlib():
    """查看相关参数"""
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    x1 = [1,2,3] 
    y1 = [5,7,4]  
    x2 = [1,2,3] 
    y2 = [10,17,14]
    
    plt.plot(x1,y1,'ro--',label='first line') # 设置线条标签
    plt.plot(x2,y2,'b-',label='Second line') # 设置线条标签
    
    # 设置标题
    plt.title("一季度进出口贸易数据")
    
    # 设置xy轴标签
    plt.xlabel("月份")
    plt.ylabel("美元/亿元")
    
    # 设置范围
    plt.xlim(0,6)
    plt.ylim(0,18)
    
    # 解决中文显示问题
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False

    # 设置刻度
    plt.xticks([1,2,3,4,5,6],[str(i)+"月" for i in range(1,7)])
    plt.yticks(np.arange(2,20,2),['200','300','400','500','600','700','800','900','1000'])
    
    # 获取坐标轴信息
    AX = plt.gca()
    # 设置边框
    AX.spines['top'].set_color('none')
    AX.spines['right'].set_color('red')
    
    # 生成默认图例
    plt.legend()
    
    plt.show()

eg_matplotlib()

学习python库matplotlib之figure常见参数和subplot绘制子图(2)_第2张图片

1.3 Matplotlib之Subplot子图

subplot:子图,figure对象下创建一个或者多个subplot对象(即axes)用于绘制图像.
subplot(numRows, numCols, plotNum)

1.3.1 面向过程版本

def eg_matplotlib():
    """面向过程绘制子图"""
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    x = np.arange(-3,3,0.1)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.sin(x)+np.cos(x)
    y4 = np.tan(x)
    
    # 设置在jupyter中matplotlib中的现实情况
    %matplotlib inline 
    
    # 解决中文显示问题
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    
    #创建图像
    plt.figure()
    
    # 第一个子图
    plt.subplot(221)
    plt.plot(x,y1,'ro--')
    # 设置xy轴标签
    plt.xlabel("x")
    plt.ylabel("y1=sin(x)")
    # 设置范围
    plt.xlim(-6,6)
    plt.ylim(-2,2)
    # 获取坐标轴信息
    AX = plt.gca()
    # 设置边框
    AX.spines['top'].set_color('none')
    AX.spines['right'].set_color('none')
    
    # 第二个子图
    plt.subplot(222)
    plt.plot(x,y2,'b--')
    
    # 设置xy轴标签
    plt.xlabel("x")
    plt.ylabel("y2=cos(x)")
    
    # 设置范围
    plt.xlim(-6,6)
    plt.ylim(-2,2)

    # 获取坐标轴信息
    AX = plt.gca()
    # 设置边框
    AX.spines['top'].set_color('none')
    AX.spines['right'].set_color('none')
    
    
    # 第三个个子图
    plt.subplot(223)
    plt.plot(x,y2,'b--')
    
    # 设置xy轴标签
    plt.xlabel("x")
    plt.ylabel("y3=sin(x)+cos(x)")
    
    # 设置范围
    plt.xlim(-6,6)
    plt.ylim(-2,2)

    # 获取坐标轴信息
    AX = plt.gca()
    # 设置边框
    AX.spines['top'].set_color('none')
    AX.spines['right'].set_color('none')
    
    # 第四个子图
    plt.subplot(224)
    plt.plot(x,y4,'b--')
        
    # 设置xy轴标签
    plt.xlabel("x")
    plt.ylabel("y2=tan(x)")
    
    # 设置范围
    plt.xlim(-4,4)
    plt.ylim(-2,2)

    # 获取坐标轴信息
    AX = plt.gca()
    # 设置边框
    AX.spines['top'].set_color('none')
    AX.spines['right'].set_color('none')
    
    plt.show()

eg_matplotlib()

学习python库matplotlib之figure常见参数和subplot绘制子图(2)_第3张图片

1.3.2 面向对象版本

面向对象形式:

  • fig = plt.figure()
  • ax = fig.add_subplot(111)
  • 返回Axes实例:
    • 参数1,子图的总行数
    • 参数2,子图的总列数
    • 参数3,子图位置
      在Figure上添加子图的常用方法如下:
def eg_oob_subplot():
    """面向对象绘制子图"""
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    x = np.arange(-3,3,0.1)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.sin(x)+np.cos(x)
    y4 = np.tan(x)
    # 设置在jupyter中matplotlib中的现实情况
    %matplotlib inline 
    
    # 解决中文显示问题
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    
    # 获取figure对象
    fig = plt.figure(figsize=(8,6))
    
    # 在figure上面创建对象
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(212)
#     ax4 = fig.add_subplot(224)
    
    # 第一个子图
    ax1.plot(x,y1,'g--')
    # 第二个子图
    ax2.plot(x,y2,'b--') 
    # 第三个个子图
    ax3.plot(x,y3,'b--')
    # 第四个子图
#     ax4.plot(x,y4,'b--')  
        
    plt.show()

学习python库matplotlib之figure常见参数和subplot绘制子图(2)_第4张图片

1.3.3 Subplots

Sublots():返回一个图像和多个子图

  • 参数:
    • nrows=x,
    • ncols=x,
    • sharex=True,
    • sharey=False,
    • gridspec_kw={‘height_ratios’:[2,2,1,1]}
  • 例:
    fig, ax = plt.subplots(2,2),其中参数分别代表子图的行数和列数,一共有 2x2 个图像。函数返回一个figure图像和一个子图ax的array列表。
def eg_subplots():
    """面向对象绘制子图"""
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    x = np.arange(-3,3,0.1)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.sin(x)+np.cos(x)
    y4 = np.tan(x)
    # 设置在jupyter中matplotlib中的现实情况
    %matplotlib inline 
    
    # 解决中文显示问题
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    
    # 获取figure对象
    fig,axes = plt.subplots(nrows = 1,ncols = 4,sharex=False,sharey=True)
   
    # axes是一个列表
    axes[0].plot(x,y1,'r')
    axes[1].plot(x,y2,'g')
    axes[2].plot(x,y3,'b')
    axes[3].plot(x,y4,'k')
    plt.ylim(-2,2)
        
    plt.show()
    
eg_subplots()

学习python库matplotlib之figure常见参数和subplot绘制子图(2)_第5张图片

  • 例子:采用subplots绘制直方图
def subplots_hist():
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    # 设置在jupyter中matplotlib中的现实情况
    %matplotlib inline 
    
    # 解决中文显示问题
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    
    # 获取figure对象
    fig,axes = plt.subplots(nrows = 2,ncols = 2,sharex=False,sharey=True)
    
    for i in range(2):
        for j in range(2):
            axes[i][j].hist(np.random.randn(100),10,color='g',alpha=0.75)
    # 调整子图之间的距离
    plt.subplots_adjust(wspace=0.5,hspace=0.5)  
    # 标题
    fig.suptitle('test',fontsize=20)
    plt.savefig('aaa.png',dpi=100)         
    plt.show()
subplots_hist()

学习python库matplotlib之figure常见参数和subplot绘制子图(2)_第6张图片

以上内容仅是代表个人总结 若有错误之处,还请批评指正,欢迎大家一起学习!

你可能感兴趣的:(python语言)