• matplotlib简介


    matplotlib是一款用于画图的软件,以下步骤建议在.ipynb中完成。

    导包

    你需要导入以下包:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import numpy as np
    
    • 1
    • 2
    • 3

    一个简单案例

    matplotlib 在 Figure上绘制图形,每一个Figure会包含多个Axes。使用matplotlib.pyplot.subplots方法创建带有AxesFigure;使用Axes.plotAxes上画数据。

    fig, ax = plt.subplots()  # Create a figure containing a single axes.
    ax.plot([1, 2, 3, 4], [1, 4, 2, 3]);  # Plot some data on the axes.
    
    • 1
    • 2

    请添加图片描述

    Figure中组件

    下图是Figure中的常用组件(components):

    请添加图片描述

    Figure

    Figure可以理解成JS中的Canvas,我们所有的图形都要在Figure中绘制。创建Figure的常用方法有以下两种plt.figure()plt.subplots()

    fig = plt.figure()  # an empty figure with no Axes
    fig, ax = plt.subplots()  # a figure with a single Axes
    fig, axs = plt.subplots(2, 2)  # a figure with a 2x2 grid of Axes
    
    • 1
    • 2
    • 3

    Axes

    Axes是一个包含在Figure中的Artist,是一块用来绘制数据的区域,它通常包含2个Axis对象或者3个Axis对象,取决于图形3D与否。每个Axes都有一个标题set_title(),x标签set_xlabel(),y标签set_ylabel()。Axes的使用体现了OOP思想。

    Axis

    Axis设置了缩放大小和限制,其中Axis由ticks(刻度,轴上的标志)和ticklabels(标志的字符串的内容)组成。tick的位置由locator决定,ticklabels的字符串由Formatter决定。

    Artists

    所有在Figure上可见的东西都是Artists:Figure,Axes,Axis,Text等。

    所接受的输入

    matplotlib的绘图函数所接受的输入数据得是numpy.array,即都得是ndarray类型的数据。

    一种面向对象的绘图思想

    建议使用OOP思想来绘图,如下所示:

    x = np.linspace(0, 2, 100)  # Sample data.
    
    # Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
    fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
    ax.plot(x, x, label='linear')  # Plot some data on the axes.
    ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
    ax.plot(x, x**3, label='cubic')  # ... and some more.
    ax.set_xlabel('x label')  # Add an x-label to the axes.
    ax.set_ylabel('y label')  # Add a y-label to the axes.
    ax.set_title("Simple Plot")  # Add a title to the axes.
    ax.legend();  # Add a legend.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    请添加图片描述

  • 相关阅读:
    《HelloGitHub》第 98 期
    博网即时通讯软件的设计与实现(附源码+课件+数据库+资料)
    算法 - 二分
    Spring Boot面试必问:启动流程
    计算机网络体系结构
    Mybatis简介
    Spring事务传播特性
    怎样在LaTeX中方便输入带圆圈的数字
    运维工程师评估错题笔记
    使用国内代理该如何开展网页抓取项目?
  • 原文地址:https://blog.csdn.net/qq_43369406/article/details/127837829