数据可视化库 matplotlib 入门 2——figure画布、axes绘图域、plot函数

上一篇文章初步介绍了matplotlib 库的安装与配置,常用套路和绘图组件。本篇介绍 matplotlib 绘制常用图表的简单步骤,包括画布和绘图域的创建、图素的设置、用 plot 函数绘制线图并设置图例、网格等。

figure 画布和 axes 绘图域的创建与设置

按照 matplotlib 绘图常用的套路,首先要创建一个 figure 画布,然后添加 axes 绘图域,最后在绘图区域中绘制图表曲线。其中,创建画布的函数 plt.figure() ,返回一个 figure 对象。用该对象的 add_axes() 方法创建一个 Axes 对象或者用 add_subplot() 方法创建一个 AxesSubplot 对象(该对象也可直接用 plt.subplot() 函数创建),即绘图(子)区域。为了更简便,也可以直接用 plt.subplots() 函数,直接创建画布和绘图域。
画布和绘图域对象有多个属性和方法,最基本的有设置标题、坐标轴名称、网格等等,具体参考下面代码示例。

  • plt.figure(num, figsize, dpi, facecolor, edgecolor, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
    num:一个整数或者字符串。默认为空,创建一个新的 figure。若是一个整数,且某个现有 figure 对象的 number 属性等于该整数,则激活该 figure 并返回该 figure;否则创建一个新的 figure。若是个字符串,则创建一个新的 figure,并将 window title 设置为该字符串。
    figsize:一个元组,指定画布以英寸为单位的高度和宽度。
    dpi:一个整数,指定 figure 的分辨率。
    facecolor:指定背景色。
    edgecolor:指定边界色。
    返回一个 figure 画布对象。
  • figure.add_axes(rect, sharex, sharey, *args, **kwargs)
    rect:一个元组或列表,代表绘图区域的 (left, bottom, width, height),四个值必须在0到1之间。
    sharex:另一个 Axes 对象,与该 Axes 共享 x 轴。
    sharex:另一个 Axes 对象,与该 Axes 共享 y 轴。
    返回一个 axes 绘图区域对象。
  • figure.add_subplot(rcp, *args,**kwargs) 或者 plt.subplot(rcp, *args,**kwargs)
    rcp:表示绘制子图的位置,第一个参数 r 表示行数,第二个参数 c 表示列数,第三个参数 p 表示正在绘图的位置。rcp 可以合并写,也可以分开。
    sharex、sharey:同上。
    返回一个 AxesSubplot 绘图子区域对象。
  • plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, width_ratios, height_ratios, subplot_kw, gridspec_kw, **fig_kw)
    nrows、ncols:子绘图区域行数、列数
    sharex、sharey:同上
    返回一个二元元组,第一个元素就是 figure 画布,第二个元素就是各个绘图域,可下标访问每个域。

示例如下:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']   # 为了支持中文显示
plt.rcParams['axes.unicode_minus'] = False     # 为了正常显示负号

fig = plt.figure('my example 1', figsize=(7.5, 5.5))
ax1 = fig.add_axes((0.1, 0.1, 0.2, 0.2))
ax2 = fig.add_axes((0.4, 0.4, 0.5, 0.5), sharex=ax1, sharey=ax1)
plt.show()

fig = plt.figure('my example 2', figsize=(8.5, 5.5))
ax1 = fig.add_subplot(2,2,1)             # ax1 = plt.subplot(221) 效果一样
ax2 = fig.add_subplot(2,2,2, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(223, sharex=ax1)
plt.show()

fig, ax = plt.subplots(2, 2, sharex=False, sharey=False, figsize=(9,6))  # 创建2行2列图表,不共享坐标轴
fig.suptitle('演示图表', fontsize=12, x=0.5, y=1)  # 设置图像标题
ax[0,0].set_title("graph 图1")           # 设置绘图域图表标题
ax[0,0].set_xlabel('图1的x轴标签')       # 设置 x 轴标签
ax[0,0].set_ylabel('图1的y轴标签')       # 设置 y 轴标签
ax[0,0].set_xticks([0,2,4,6])            # 设置 x 轴刻度
ax[0,0].set_yticks([-1,0,1])             # 设置 y 轴刻度
ax[0,1].set_xlim(0,10)                   # 设置 x 轴取值范围
ax[0,1].set_ylim(-10,10)                 # 设置 y 轴取值范围
ax[1,0].set_yscale("log")                # 设置 y 轴为对数坐标
ax[1,1].set_xticklabels(['zero','two','four','six','eight','ten'])  # 设置 x 轴刻度标签
plt.show()

plot 函数绘图与相关设置

axes.plot(*args, **kwargs) 是 Axes 绘图域的基本方法,它将一个数组的值与另一个数组的值绘制成线标记,具有可选格式的字符串参数,用来指定线型、标记颜色、样式以及大小。最简单的用法是 plot(x,y),其中x为数据点的横坐标,y为数据点的纵坐标,此时采用默认线型和颜色;可省略x直接用 plot(y),此时x默认为[0,1,…,len(y)-1]。设置线型和颜色 plot(x,y,‘bo’),'bo’表示格式化字符串,'b’代表颜色为蓝色,'o’代表使用小圆圈标记数据点。如果x/y为二维数组,则每一行作为一组 line 来绘制,也可以用 plot(x1,y1,‘b+’,x2,y2,‘b-’,x3,y3,‘bo’) 一次绘制多条线。

  • 控制颜色的字符串可以为: ‘b’/‘g’/‘r’/‘c’/‘m’/‘y’/‘k’/‘w’(蓝、绿、红、青、品红、黄、黑、白),也可以指定全名(比如 ‘red’);或者指定十六进制字符串(比如 #00ff00);或者指定一个 RGB/RGBA 元组(比如 (0,1,0)/(0,1,0,1))。
  • 控制线型和标记符号的字符串可以为:‘-’ / ‘–’ / ‘-.’ / ‘:’ / ‘.’ / ‘,’ / ‘o’ / ‘v’ / ‘^’ / ‘<’ / ‘>’ / ‘1’ / ‘2’ / ‘3’ / ‘4’ / ‘s’ / ‘p’ / ‘*’ / ‘h’ / ‘H’ / ‘+’ / ‘x’ / ‘D’ / ‘d’ / ‘|’ / ‘_’

axes.legend(*args, **kwargs) 是 Axes 绘图域绘制图例的基本方法(figure 或 plt 也有 legend 方法绘制图例),用法是先创建一个 Axes,然后在其中添加 lines,再直接调用 ax.legend(),此时那些label非空的线将被图例注释。也可先创建 line,然后调用 line.set_label(),再调用 ax.legend()。函数常用参数中 labels 是一个字符串序列,用来指定标签的名称,loc 是指定图例位置的参数,其他参数见示例代码:

  • loc 指定图例的位置,可以为整数或者字符串:‘best’ / ‘upper right’ / ‘upper left’ / ‘lower left’ / ‘lower right’ / ‘right’ / ‘center left’ / ‘center right’ / ‘lower center’ / ‘upper center’ / ‘center’,对应于整数的 0~10。也可以指定坐标(x,y),其中(0,0)是左下角,(1,1)是右上角。

示例1:

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.arange(1, 11)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, np.exp(x), 'b--')                       # 绘制指数曲线,蓝色虚线
ax1.set_ylabel('exp', fontsize=14)
ax2 = ax1.twinx()                                   # 添加双轴
ax2.plot(x, np.log(x), 'ro-', markersize=10)        # 绘制对数曲线,红色带圆点实线
ax2.set_ylabel('log', fontsize=14)
fig.legend(labels=('exp','log'), loc='upper left')  # 在画布的左上角绘制图例
plt.show()  # 绘制图像如下所示

上述代码绘制图像如下:
在这里插入图片描述
示例2:

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-3,3)

fig = plt.figure(figsize=(9,7))
ax1 = fig.add_subplot(221)
ax1.set_title("图1")
ax1.plot(x, np.exp(x), 'c+', label=r'exp(x)')
ax1.plot(x, x ** 2, 'g*', label=r'$x^2$')
ax1.set_xlim(-3, 3)   # 设置坐标范围
ax1.legend()          # 绘制图例
ax1.grid()            # 绘制网格

ax2 = fig.add_subplot(222)
ax2.set_title("图2")
line1 = ax2.plot(x, np.sin(x), 'm-')[0]
line1.set_label(r'sin(x)')
line2 = ax2.plot(x, np.cos(x), 'rs')[0]
line2.set_label(r'cos(x)')
ax2.legend(loc='lower right', fontsize=16, framealpha=0.4)  # 右下角绘制图例,图例文字大小为16,透明度为0.4
ax2.grid(color='b', ls = '-.', lw = 0.35)  # 绘制网格,网格线为蓝色点划线,线宽0.35

ax3 = fig.add_subplot(223)
ax3.set_title("图3")
line3 = ax3.plot(x, 0.5*x-2, 'kv')[0]
line4 = ax3.plot(x, 2*x+1, 'g+')[0]
ax3.legend((line3,line4),(r'0.5*x-2',r'2*x+1'),loc='center left')  # 左边中间位置绘制图例

ax4 = fig.add_subplot(224)
ax4.set_title("图4")
ax4.set_xlabel('x轴标签')
ax4.set_ylabel('y轴标签')
ax4.plot(x, -x ** 2 , 'b-', label=r'$-x^2$')
ax4.plot(x, x ** 3, 'rx', label=r'$x^3$')
ax4.legend(loc='upper center', frameon=False)   # 上方中间位置绘制图例,图例边框取消
plt.show()

上述代码绘制图像如下:
在这里插入图片描述

以上。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值