matplotlib简介

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

导包

你需要导入以下包:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

一个简单案例

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.

请添加图片描述

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

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.

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值