pyplot绘图区域

2023-06-05,,

pyplot绘图区域

Matplotlib图像组成

matplotlib中,整个图像为一个Figure对象,与用户交互的整个窗口
Figure对象中包含一个或多个Axes(ax)子对象,每个ax子对象都是一个拥有自己坐标系的绘图区域


创建figure窗口对象

plt.figure(num=None, figsize=None, dpi=None, facecolor=N)

num,num=n,选择图表n或创建图表n,给figure赋与编号
figsize,图像尺寸,figsize=(4,8)
facecolor,背景颜色

import matplotlib.pyplot as plt

plt.figure()
plt.plot([1,2,3]) plt.figure(2, figsize=(4,4), dpi=80, facecolor='#ff0000')
plt.plot([1,3,2]) plt.show()



绘图时,如果不设置figure窗口和ax子窗口,Matplotlib会自动创建一个figure窗口和一个ax子窗口subplots(111)

import matplotlib.pyplot as plt

#生成图像

#简写
plt.plot([1,2,3]) ######################### #等价于正常写法
plt.figure() # 创建figure,默认值为1
plt.subplot(111) #创建ax,默认值111
plt.plot([1,2,3]) #绘图 ######################### #面向对象的写法,将窗口对象赋给变量
fig, ax = plt.subplots() # 常用的面向对象简写方式
#上面代码等价于:
#fig = plt.figure()
#ax = fig.add_subplot(111) ax.plot([1,2,3]) plt.show()

 


多个ax子对象

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False)

nrows,选中子图行数
ncols,选中子图列数
sharex,是否共享X轴(True共享,Flase不共享,col每列共享,row每行共享)
sharey,是否共享Y轴
figsize,figsize=(5,10),给本figure设置大小

import matplotlib.pyplot as plt

fig, ax = plt.subplots(3,2)
# fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharex=False, sharey=True) ax[0, 1].plot([1,2,3]) #0,1表示选中第0行第1列的ax子图 plt.show()


绘图区域:将一个大图分隔为多个子图,分别绘图,同时输出


简单绘图区域:plt.subplot

plt.subplot(nrows,ncols,plot_number)

nrows,横轴数量,类似表格的 行
ncols,纵轴数量,类似表格的 列
plot_number,当前绘图区域

例子:

import matplotlib.pyplot as plt

plt.subplot(3,2,1) #绘制3行两列6个子图,当前绘制第1个(从左上角横排往右下角数)
plt.plot([1,2,3]) plt.subplot(3,2,2)
plt.plot([1,3,2]) plt.subplot(3,2,3)
plt.plot([2,1,3]) plt.subplot(3,2,4)
plt.plot([2,3,1]) plt.subplot(3,2,5)
plt.plot([3,1,2]) plt.subplot(3,2,6)
plt.plot([3,2,1]) plt.show()


如果是横纵行列都是个位数,可以去掉逗号plt.subplot(324)


复杂绘图区域:pyplot子绘图区域

设定网格,选中网格,确定选中行列区域数量,编号从0开始

plt.subplot2grid(GridSpee,CurSpee,rowspan=1,colspan=1)

GridSpee:元组,这个图表共有几行几列

例如(3,3),表示将区域分隔成3行3列9块区域
CurSpee:当前选中第几行第几列的子图表
例如(1,0),这里表示第1行第0列(行列都以0开头)
rowspan:合并行
例如rowspan=2,合并本块和下方块
conlspan:合并列
例如colspan=3,合并本块和右侧两块

例子:

import matplotlib.pyplot as plt

plt.subplot2grid((4,3),(0,0),colspan=3) #4行3列,选中0行0列单元格,合并3列
plt.subplot2grid((4,3),(1,0),rowspan=2,colspan=2) # 选中1行0列单元格,合并2行,合并2列
plt.subplot2grid((4,3),(1,2),rowspan=2) #选中1行2列单元格,合并2行
plt.plot([2,3,1])
plt.subplot2grid((4,3),(3,0)) #选中3行0列单元格
plt.subplot2grid((4,3),(3,1)) #选中3行1列单元格
plt.subplot2grid((4,3),(3,2)) #选中3行2列单元格 plt.show()



pyplot绘图区域的相关教程结束。

《pyplot绘图区域.doc》

下载本文的Word格式文档,以方便收藏与打印。