matplotlib是基于Python语言的开源项目,旨在为Python提供一个数据绘图包。使用matplotlib绘图时,必须理解画布(figure),区域(axe)和坐标轴(axis)的区别。figure是画布,而区域axe是画布上的一个子图(subplot),axis是子图上的坐标系。
下图显示了figure(画布)、axes(坐标系)、axis(坐标轴)三者之间的关系。
一,导入相关库
导入常用的库,并设置画布的参数:
importnumpy as npimportpandas as pdimportmatplotlib as mplimportmatplotlib.pyplot as plt#排除警告信息
importwarnings
warnings.filterwarnings("ignore")#打印版本信息
display(np.__version__)
display(pd.__version__)
display(mpl.__version__)#matplotlib画图常见参数设置
mpl.rcParams["font.family"] = "SimHei" #设置字体
mpl.rcParams["axes.unicode_minus"]=False #用来正常显示负号
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
#嵌入式显示图形
%matplotlib inline
二,创建画布
创建画布的方式有显式和隐式两种,本文显式创建画布,添加子图,并设置子图在画布中的位置:
#手动创建一个figure对象
figure =plt.figure()#获取每个位置的axes对象
axes1 = figure.add_subplot(2,1,1)
axes2= figure.add_subplot(2,1,2)
函数add_subplot()的功能:切分画布,指定当前子图的区域,并返回该区域的引用。
在绘图完成之后,可以通过plt.show() 或者figure.show()把图形显示出来。
举例说明,在一块画布中绘制两个折线图:
figure =plt.figure()
axes1= figure.add_subplot(2,1,1)
axes2= figure.add_subplot(2,1,2)
axes1.plot([1,3,5,7],[4,9,6,8])
axes2.plot([1,2,4,5],[8,4,6,2])
plt.show()
三,细节设置
* figure 画布
* axes 坐标系,一个画布上可以有多个坐标系
* axis 坐标轴,一个坐标系中可以有多个坐标轴,一般都是二维平面坐标系,或者三维立体坐标系
* title 标题
* legend 图例
* grid 背景网格
* tick 刻度
* axis label 坐标轴名称
* tick label 刻度名称
* major tick label 主刻度标签
* minor tick label 副刻度标签
* line 线
* style 线条样式
* marker 点标记
* font 字体相关
参考文档: