机器学习:Matplotlib之sublplot函数

Matploblib介绍

Matplotlib 是Python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib;
matplotlib概念介绍:
在这里插入图片描述

Figure

在任何绘图之前,我们需要一个Figure对象,可以理解成我们需要一张画布才能开始绘图

import matplotlib.pyplot as plt
fig = plt.figure()

Axes

在拥有Figure对象之后,在作画前我们还需要轴,没有轴的话就没有绘图基准,所以需要添加Axes,Axes代表的则是纸中的一片区域(当然可以有多个区域,这是后续要说到的subplots)

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[0.5, 3.5], ylim=[-2, 6], title='An Example Axes',
       ylabel='Y-Axis', xlabel='X-Axis')
plt.show()

在这里插入图片描述
通过图片可知:
1.ax.set设置坐标轴名称(ylabel,xlabel)及取值范围(xlim,ylim)还可以增加主题(title)
思考:fig.add_subplot(111)中111代表什么?

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
plt.show()

在这里插入图片描述
通过图片可知:
1.生成4个相等的区域;4=22
2.通过fig.add_subplot(2, 2, 1)或fig.add_subplot(221)的方式生成Axes,前面两个参数确定了面板的划分,例如 2, 2会将整个面板划分成 4 块区域,第三个参数取值范围是 [1, 2
2] 表示第几个区域

sublplot函数

axes 采用我们常用二维数组的形式访问;

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0,0].set(title='Upper Left')
axes[0,1].set(title='Upper Right')
axes[1,0].set(title='Lower Left')
axes[1,1].set(title='Lower Right')
plt.show()

在这里插入图片描述

示例

import matplotlib.pyplot as plt
import numpy as np 
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0=axes[0,0]
ax0.set(title='Upper Left')
ax1=axes[0,1]
ax1.set(title='Upper Right')
ax2=axes[1,0]
ax2.set(title='Lower Left')
ax3=axes[1,1]
ax3.set(title='Lower Right')

x = [1, 2, 3, 4]
y1 = [1, 2, 3, 4]
y2 = [1, 4, 9, 16]
y3 = [2, 6, 6, 8]
y4 = [1, -3, 5, 7]

ax0.plot(x, y1, 'r')
ax1.plot(x, y2)
ax2.plot(x, y3,'g')
ax3.plot(x, y4,'y')
plt.show()

在这里插入图片描述

subplots_adjust函数

plt.subplots_adjust():调整子图间的距离

plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
                wspace=None, hspace=None)

参数解释:
left:默认为0.125,子图(subplot)距画板(figure)左边的距离
right:默认为0.9,子图(subplot)距画板(figure)右边的距离
bottom:默认为0.1,子图(subplot)距画板(figure)底部的距离
top:默认为0.9,子图(subplot)距画板(figure)顶部的距离
wspace:默认为0.2,子图水平间距
hspace:默认为0.2,子图垂直间距

示例

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [1, 2, 2, 4]
y2 = [1, 4,8, 16]
y3 = [2, 6, 6,9]
y4 = [1, -3, 6, 7]
plt.figure()
plt.subplot(221)
plt.plot(x, y1, 'r')
plt.subplot(222)
plt.plot(x, y2)
plt.subplot(223)
plt.plot(x, y3,'g')
plt.subplot(224)
plt.plot(x, y4,'y')
plt.subplots_adjust(hspace=0.5, wspace=0.5)
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值