注:部分内容参考了:https://blog.csdn.net/helunqu2017/article/details/78662877?
#导入需要的包
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
%matplotlib inline
1.先建画板
语法:figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
- num:图像编号或名称,数字为编号 ,字符串为名称
- figsize:指定figure的宽和高,单位为英寸
- dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80
- facecolor:背景颜色
- edgecolor:边框颜色
- frameon:是否显示边框
#1.建画板fig
fig1=plt.figure("我是画板1",figsize=(10,8),dpi=100,facecolor="r",edgecolor="blue",frameon=True)
plt.show()
2."贴"画纸ax,但是要创建子图(即选择“贴”在画板fig的哪个位置,若有多个子图就涉及到各子图的排版问题)
**法1.subplot(nrows,ncols,sharex,sharey,subplot_kw,fig_kw)创建单个子图
- nrows:subplot的行数;
- ncols:subplot的列数;
- sharex:所有subplot应该使用相同的x轴刻度(调节xlim将会影响所有subplot);
- sharey:所有subplot应该使用相同的y轴刻度(调节ylim将会影响所有subplot);
- subplot_kw:用于创建个subplot关键字字典;
- **fig_kw:创建figure时的其他关键字,如:plt.subplots(2,2,figsize=(8,6))
x=np.arange(0,100)#numpy.arange([start, ]stop, [step, ]dtype=None)
#做图1
ax1=plt.subplot(231)
plt.plot(x,x)
#做图2
ax1=plt.subplot(235)
plt.plot(x,-x,color="red",linewidth=5)
#做图3
ax1=plt.subplot(233)
plt.plot(x,x**2)
#做图4
ax1=plt.subplot(232)
plt.plot(x**2,x)
#做图5
ax1=plt.subplot(234)
plt.plot(x**2,-x)
#做图6
ax1=plt.subplot(236)
plt.plot(x**2,1/x)
matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
plt.plot()参数参考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
法2.subplots创建多个子图
subplots()参数与subplot()类似。
fig2,axes=plt.subplots(2,2)
ax1=axes[0,0]#子图编号是从0开始的
ax2=axes[0,1]
ax3=axes[1,0]
ax4=axes[1,1]
#作图1
ax1.plot(x, x)
#作图2
ax2.plot(x, -x)
#作图3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.8)
#作图4
ax4.plot(x, np.log(x))
plt.show()
法3.面向对象API:add_subplots与add_axes新增子图或区域
add_subplot与add_axes都是面对象figure编程的,pyplot api中没有此命令
add_subplot的参数与subplots的相似
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
#新建figure对象
fig=plt.figure()
#新建子图1
ax1=fig.add_subplot(2,2,1)
ax1.plot(x, x)
#新建子图3
ax3=fig.add_subplot(2,2,3)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#新建子图4
ax4=fig.add_subplot(2,2,4)
ax4.plot(x, np.log(x))
plt.show()
``
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200615204116239.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0tvbmdqaWFuZ2V6aQ==,size_16,color_FFFFFF,t_70)
add_axes为新增子区域,该区域可以座落在figure内任意位置,且该区域可任意设置大小
add_axes参数可参考官方文档:http://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure