首页 > 其他 > 详细

【数据分析】matplotlib——使用add_subplot和GridSpec自定义子图

时间:2019-11-12 18:00:00      阅读:303      评论:0      收藏:0      [点我收藏+]

在一张画布上定义多张子图:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import gridspec

生成几个随机点:

random_cp = np.random.random_integers(1, 100, (100, 2))
random_nums = np.random.random_integers(1, 100, 100)
random_cp1 = np.random.random_integers(1, 100, (100, 2))
random_nums1 = np.random.random_integers(1, 100, 100)

1、使用add_subplot

通过add_subplot就可以实现子图的划分:

先是通过plt.figure()创建画布,之后再通过add_subplot()在画布上创建不同的区域。

其中add_subplot()的参数,类似221就是将画布分为2行2列的也就是2×2的区域,使用第1个区域。

fig1 = plt.figure()
 
ax1 = fig1.add_subplot(221)
ax2 = fig1.add_subplot(222)
 
ax3 = fig1.add_subplot(223)
ax4 = fig1.add_subplot(224)
 
ax1.plot(range(len(random_nums)), random_nums)
ax3.scatter(random_cp[:, 0], random_cp[:, 1])
ax4.plot(range(len(random_nums1)), random_nums1)
ax2.scatter(random_cp1[:, 0], random_cp1[:, 1])
 
plt.show()

2、使用GridSpec

先是通过gridspec.GridSpec()创建区域,参数5,5的意思就是每行五个,每列五个,最后就是一个5×5的画布,相比于add_subplot(),使用网格布局的话可以更加灵活的控制占用多少空间。

gs = gridspec.GridSpec(5,5)
fig1 = plt.figure()
ax1 = fig1.add_subplot(gs[0:2, 0:2])
ax2 = fig1.add_subplot(gs[3:5, 0:2])
 
ax3 = fig1.add_subplot(gs[0:2, 3:5])
ax4 = fig1.add_subplot(gs[3:5, 3:5])
 
ax1.plot(range(len(random_nums)), random_nums)
ax3.scatter(random_cp[:, 0], random_cp[:, 1])
ax4.plot(range(len(random_nums1)), random_nums1)
ax2.scatter(random_cp1[:, 0], random_cp1[:, 1])
 
ax1.plot(range(len(random_nums)), random_nums)
ax3.scatter(random_cp[:, 0], random_cp[:, 1])
ax4.plot(range(len(random_nums1)), random_nums1)
ax2.scatter(random_cp1[:, 0], random_cp1[:, 1])
 
plt.show()

 

【数据分析】matplotlib——使用add_subplot和GridSpec自定义子图

原文:https://www.cnblogs.com/ITCSJ/p/11843813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!