首页 > Python资料 博客日记

matplotlib多图合一的四种实现(多张图显示在一个figure中)

2024-03-17 07:00:04Python资料围观135

这篇文章介绍了matplotlib多图合一的四种实现(多张图显示在一个figure中),分享给大家做个参考,收藏Python资料网收获更多编程知识

Subplot多合一显示

1 plt.subplot

使用plt.subplot(rownum, columnnum, index)说明新图纸是几行几列的

import matplotlib.pyplot as plt

plt.figure()
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])

plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 1])

plt.subplot(2, 1, 2)
plt.plot([0, 1], [0, 1])

plt.show()

2 plt.subplot2grid

使用plt.subplot2grid(总格数, 起始格数, rowspan, colspan)来绘制

import matplotlib.pyplot as plt

plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2], [1, 2])
# 设置某属性的时候需要在前面加set_
ax1.set_title("ax1 title")

ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

plt.tight_layout()
plt.show()

3 gridspec.GridSpec

首先使用gridspec.GridSpec(rownum, colnum)声明将figure分割成几块,然后在绘图时使用切片声明使用哪几块即可

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure()
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :2])
ax3 = plt.subplot(gs[1:, 2])
ax4 = plt.subplot(gs[2, 0])
ax5 = plt.subplot(gs[2, 1])

plt.tight_layout()
plt.show()

4 plt.subplots

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.plot([1, 2], [1, 2])

plt.tight_layout()
plt.show()


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐