matplotlib 创建图和子图

Matplotlib 可能是 Python 2D-绘图领域使用最广泛的套件。它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式。这里将会探索 matplotlib 的常见用法。

../../_images/anatomy.png

plt方式是先生成了一个画布,然后在这个画布上隐式的生成一个画图区域来进行画图;ax是先生成一个画布,然后,我们在此画布上,选定一个子区域画了一个子图,上一张官方的图,看看你能不能更好的理解。

img

# 创建一个宽3高4的画布,画布背景是红色
plt.figure(facecolor="red", figsize=(3, 4))
ax = plt.plot(range(1000,2000))
plt.show()

image-20231111160638860

通过subplot函数创建单个子图

nums = np.arange(1, 101)
# 将画布分为2行2列区域,占用编号为1的区域,就是第一行第一列的区域
plt.subplot(2, 2, 1)
plt.plot(nums, nums)

# 将画布分为2行2列区域,占用编号为2的区域,就是第一行第二列的区域
plt.subplot(222)
plt.plot(nums, -nums)

# 将画布分为2行1列区域,占用编号为2的区域,就是第二行全部
plt.subplot(212)
plt.plot(nums, nums ** 2)

image-20231111161242683

通过subplots函数创建多个子图

nums = np.arange(1, 101)

# 将画布分为2行2列区域,并返回子图数组axes
fig, axes = plt.subplots(2, 2)
# 根据索引获取对应区域位置
ax1 = axes[0, 0]
ax2 = axes[0, 1]
ax3 = axes[1, 0]
ax4 = axes[1, 1]

# 在子图上作图
line1 = ax1.plot(nums, nums)
ax2.plot(nums, -nums)
ax3.plot(nums, nums ** 2)
ax4.plot(nums, np.log(nums))
plt.show()

image-20231111161758867

通过add_subplot方法添加和选中子图

# 创建画布实例
fig = plt.figure()

# 添加子图
fig.add_subplot(221)
fig.add_subplot(222)
fig.add_subplot(224)
fig.add_subplot(223)

# 默认在最后一次使用的subplot的位置上作图
random_num = np.random.randn(100)
plt.plot(random_num)
plt.show()

image-20231111162221927

在选中的子图上作图

# 创建画布
fig = plt.figure()

# 添加子图
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)

# 在指定子图上进行作图
random_num = np.random.randn(100)
ax2.plot(random_num)
plt.show()

image-20231111162449586

调整子图间距

# 将画布分为2行2列区域,并返回子图数组axes
fig, axes = plt.subplots(2, 2, sharex = True, sharey = True)
axes[0, 0].plot(np.random.randn(100))
axes[0, 1].plot(np.random.randn(100))
axes[1, 0].plot(np.random.randn(100))
axes[1, 1].plot(np.random.randn(100))

# 调整间距
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

image-20231111162902329

【精选】matplotlib.pyplot的使用总结大全(入门加进阶)_wswguilin的博客-CSDN博客

JupyterLab (gesis.org)

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

golemon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值