Python中的Matplotlib

Matplotlib

Matplotlib由大量可视化库组成

matplotlib.pyplot是绘制各类可视化图形的命令子库,相当于快捷方式。

import matplotlib.pyplot as plt

plot绘图函数

Python中的Matplotlib

![在这里插入图片描述](https://img-blog.****img.cn/20190125175649684.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0Vyb2JlcmVy,size_16,color_FFFFFF,t_70

Python中的Matplotlib

对于plot来说,如果只有一个值,则会被当作y轴处理,x轴是其索引。
使用savefig方法存为PNG文件,dpi修改输出质量
Python中的Matplotlib

plt.plot(x, y) #当有两个以上参数时,按X轴、Y轴顺序绘制数据点
plt.axis([-1, 10, 0, 6]) #管理横纵坐标尺度
#X轴起始于-1,终止于10,纵轴起始于0,终止于6

Python中的Matplotlib

Python中的Matplotlib
subplot(nrows, ncols, plot_number)函数分割图形区域,在全局绘图区域中创建一个分区体系,并定位到一个子绘图区域。
可以去掉逗号

plot.subplot(3, 2, 4)
plot.subplot(324)

Python中的Matplotlib

左上角第一个开始编号

Python中的Matplotlib

Python中的Matplotlib

import matplotlib
matplotlib.rcParams['front.family'] = 'SimHei'
#可使图形中显示中文(黑体)

文本显示

函数 说明
plt.xlabel() 对X轴增加文本标签
plt.ylabe() 同上
plt.title() 对图形整体增加文本标签
plt.text() 在任意位置增加文本
plt.annotate() 在图形中增加带箭头的注解

Python中的Matplotlib

Python中的Matplotlib
text参数:第一、第二为文本对应坐标值
grid函数:参数为True时,加入网格曲线

plt.annotate(s, xy = arrow_crd, xytext = text_crd, arrowprops = dict)
s表示要注解的字符串
xy表示箭头所在位置
xytext表示文本所在位置
arrowprops定义字典类型,表示箭头显示的属性

Python中的Matplotlib
Python中的Matplotlib
shrink 对于文本和图像留一定的缩进

子绘图区域

subplot2grid方法

plt.subplot2grid(GridSpec, CurSpec, colspan = 1, rowspan = 1)
# 设定网格,选中网格, 确定选中行列区域数量,编号从0开始

第一个参数为元组,表示将一个区域分割成什么样的网格形状
第二个参数为元组,表示当前为Subplot选中的位置
colspan表示列的方向上,延申几个长度
rowspan同理
Python中的Matplotlib

gridspec方法

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(3, 3)
#网格保存为gs变量
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :-1])
ax3 = plt.subplot(gs[1:, -1])
ax4 = plt.subplot(gs[2, 0])
ax5 = plt.subplot(gs[2, 1])

结果同上

pyplot基础图表函数概述

绘图函数

函数 说明
plt.plot(x, y, fmt, …) 绘制一个坐标图
plt.boxplot(data, notch, position) 绘制一个箱型图
plt.bar(left, height, width, bottom) 绘制一个条形图
plt.barh(width, bottom, left, height) 绘制一个横向坐标图
plt.polar(theta, r) 绘制极坐标图
plt.pie(data, explode) 绘制饼图
plt.psd(x, NFFT = 256, pad_to, Fs) 绘制功率谱密度图
plt.specgram(x, NFFT = 256, Fs) 绘制谱图
plt.cohere(x, y, NFFT = 256, Fs) 绘制X-Y相关性函数
plt.scatter(x, y) 绘制散点图,其中,x和y同步长
plt.step(x, y, where) 绘制步阶图
plt.hist(x, bins, normed) 绘制直方图
plt.contour(X, Y, Z, N) 绘制等值图
plt.vlines() 绘制垂直图
plt.stem(x, y, linefmt, marketfmt) 绘制柴火图
plt.plot_date() 绘制数据日期

饼图绘制

Python中的Matplotlib

Python中的Matplotlib

explode凸出部分
autopct显示百分数的格式
shadow带阴影与否
startangle饼图起始角度

使饼图变为正圆形
Python中的Matplotlib
Python中的Matplotlib

直方图绘制

Python中的Matplotlib

Python中的Matplotlib

Python中的Matplotlib

Python中的Matplotlib
数组a的取值范围划分为bin个区间
第二个参数为bin:直方图中直方的个数
normed = 1 纵坐标为概率, 0为个数

极坐标图的绘制

Python中的Matplotlib

N绘制极坐标数据的个数
使用projection参数的值为polar,绘制极坐标图
使用.bar方法,theta,radii,width分别对应left,height,width
left:图中开始绘制的位置
height:中心点向边缘绘制的长度
width:每个绘图区域的面积,以度辐射的面积
for循环设定颜色

Python中的Matplotlib

修改参数
Python中的Matplotlib
Python中的Matplotlib

散点图的绘制

Python中的Matplotlib
Python中的Matplotlib

绘图对象为ax,面向对象方法
所有的函数,均变为对象的方法