概述
matplotlib 四
- matplotlib多图布局
- 1. 解决元素重叠问题
- 2. 自定义布局方式
- 3. 散点图与直方图合并
matplotlib多图布局
1. 解决元素重叠问题
我们在作图时,一个Figure对象可能会生成多个Axes对象。
例如:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
# 创建一个作图函数
def set_plot(ax, fontsize=14):
ax.plot([1,2,3],[1,3,2])
ax.set_xlabel('x - 轴')
ax.set_ylabel('y - 轴')
ax.set_title('折线图')
# 使用Figure和Axes容器来设置图
fig, axes = plt.subplots(2, 2)
fig.set_facecolor('c')
# 调用set_plot函数
set_plot(axes[0, 0])
set_plot(axes[0, 1])
set_plot(axes[1, 0])
set_plot(axes[1, 1])
结果显示:
可以看到,上下图的图形元素有重叠部分。
为了避免多个图重叠,可以使用fig.tight_layout()
或fig.subplots_adjust()
(1). fig.tight_layout()
fig.tight_layout()
结果:
(2).fig.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
fig.subplots_adjust(0,0,1,1,hspace=0.5,wspace=0.5)
结果:
2. 自定义布局方式
设置各个图不是均等分,而是某些图占据原来多个图的位置。
(1). 简单布局实现
可以直接使用subplots来实现:
# 2*3为最大子图
ax1 = plt.subplot(231)
ax2 = plt.subplot(234)
# 在2*3最大子图的基础上,进行合理填补
ax3 = plt.subplot(132)
ax4 = plt.subplot(133)
plt.tight_layout()
结果:
(2). 复杂布局实现
需要采用GridSpec对象来实现:
# 创建画布
fig = plt.figure()
# 利用画布,创建GridSpec对象
gs = fig.add_gridspec(x, y)
# 利用GridSpec对象填充子图
fig.add_subplot(gs[y1, x1])
例子:
fig = plt.figure()
fig.suptitle("gs[y, x]所形成的图形", x=0.5, y=1.2, fontsize=20)
# 创建4*4的对象
gs = fig.add_gridspec(4, 4)
# 创建第一行
ax1 = fig.add_subplot(gs[0,0:4])
ax1.set_title('[0,0:4]')
# 创建中间四行
ax2 = fig.add_subplot(gs[1,1:3])
ax2.set_title('[1,1:3]')
ax3 = fig.add_subplot(gs[2:4,1])
ax3.set_title('[2:4,1]')
ax4 = fig.add_subplot(gs[2,2])
ax4.set_title('[2,2]')
ax5 = fig.add_subplot(gs[3,2])
ax5.set_title('[3,2]')
# 创建两边两列
ax6 = fig.add_subplot(gs[1:4,3])
ax6.set_title('[1:4,3]')
ax7 = fig.add_subplot(gs[1:4,0])
ax7.set_title('[1:4,0]')
plt.tight_layout()
结果显示:
注意:gs[y, x]中,y是纵方向,x是横方向
接上一步举例,调整图的比例:(按照GridSpec(x,y)中x与y对应的横坐标与纵坐标的数值作为长度来设置比例)
加上变量:
width = (1,2,1,2)
height = (2,2,1,1)
加上参数:
gs = fig.add_gridspec(4, 4, width_ratios=width, height_ratios=height)
(3). 手动设置位置
通过add_axes()来设置位置:
# add_axes的方式
fig = plt.figure()
fig.add_subplot(211)
fig.add_axes([0.4,0.4,0.8,0.8])
通过set_position()来设置位置:
fig,axes = plt.subplots(1,1)
axes[1].set_position([0.4,0.4,0.8,0.8])
3. 散点图与直方图合并
数据集,这里我用随机数组:
male_athletes = pd.DataFrame(np.random.randint(0,220,size=(200,2)), columns=["Height", "Weight"])
合并实现:
fig = plt.figure(figsize=(8,8))
widths = (2,0.5)
heights = (0.5,2)
gs = fig.add_gridspec(2,2,width_ratios=widths,height_ratios=heights)
# 顶部的直方图
ax1 = fig.add_subplot(gs[0,0])
ax1.hist(male_athletes['Height'],bins=20)
for tick in ax1.xaxis.get_major_ticks():
tick.label1On = False
# 中间的散点图
ax2 = fig.add_subplot(gs[1,0])
ax2.scatter('Height','Weight',data=male_athletes)
# 右边的直方图
ax3 = fig.add_subplot(gs[1,1])
ax3.hist(male_athletes['Weight'],bins=20,orientation='horizontal')
for tick in ax3.yaxis.get_major_ticks():
tick.label1On = False
fig.tight_layout(h_pad=0,w_pad=0)
结果显示:
最后
以上就是超帅麦片为你收集整理的matplotlib (四) 多图布局问题matplotlib多图布局的全部内容,希望文章能够帮你解决matplotlib (四) 多图布局问题matplotlib多图布局所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复