学习方式:(点击这里TP)
[官网examples入门学习] https://matplotlib.org/examples/index.html
https://matplotlib.org/galler.html
- 安装方式
pip install matplotlib
- 导入方式
import matplotlib.pyplot as plt
- 基础操作
plot(x,y,color='red',linestyle='dashed',marker='o')
x,y :输入的样本点坐标值
color:线的颜色
linestyle:线的样式
marker:样本点的样式
label:线型名称
- linestyle 线的样式
线型 | 说明 |
---|---|
- | 实线(默认) |
– | 双划线 |
: | 虚线 |
:. | 点划线 |
- marker 标记符
标记符 | 说明 | 标记符 | 说明 |
---|---|---|---|
+ | 加号符 | s | 正方形 |
o | 空心圆 | d | 菱形 |
* | 星号 | v | 下三角形 |
. | 实心圆 | ^ | 上三角形 |
X | 叉号符 | > | 右三角形 |
- color颜色代码
颜色 | 说明 | 颜色 | 说明 |
---|---|---|---|
r | 红色 | m | 洋红色 |
g | 绿色 | y | 黄色 |
b | 蓝色 | k | 黑色 |
c | 青绿色 | w | 白色 |
常用绘图操作
- 多条折线图在一张图像中显示
plot(x1, y1, x2, y2, x3, y3)
# 一张图中绘制多条折线
plt.plot([1, 2, 3], [1, 2, 3], [1, 2, 3], [3, 1, 2], [1, 2, 3], [3, 2, 1])
plt.show()
"""
上下两种写法效果一样
"""
# 分开描述
plt.plot([1, 2, 3], [3, 2, 1])
plt.plot([1, 2, 3], [3, 1, 2])
plt.plot([1, 2, 3], [1, 2, 3])
plt.show()
- 直接赋值 y 值, x 是np.arange(n)
plt.plot([3, 1, 2], color='red')
plt.grid()
plt.show()
- 添加图例
plt.legend()
# 生成图例
plt.plot([1, 2, 3])
plt.plot([3, 1, 2])
plt.legend(['x', 'y'], loc='upper center') # 生成图例
plt.show()
"""
参数loc可取值,图例显示的位置
"""
'best' : 0 (自适应方式)
'upper right' : 1
'upper left' : 2
'lower right' : 3
'lower right' : 4
'right' : 5
'center left' : 6
'cneter right' : 7
'lower center' : 8
'upper center' : 9
'center' : 10
- 添加 x,y轴标签
plt.xlabel(‘轴标签名’)
plt.ylaber(‘轴标签名’) - 添加标题
plt.title(‘标题名’) - 添加网格线
plt.grid()
中文乱码问题
plt.plot([1,3, 5, 2])
plt.title('演示图')
plt.show()
- 解决方法:
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体格式为黑体
plt.rcParams['axes.unicode_minus'] = False # 使用编码格式
- 子图
plt.subplot(numRows行数,numCols列数,plotNum图像所在位置)
# 两行两列的子图
plt.subplot(2, 2, 1)
plt.plot([1, 3, 2])
plt.subplot(2, 2, 2)
plt.plot([2, 1, 5])
plt.subplot(2, 2, 3)
plt.plot([4, 1, 6])
plt.subplot(2, 2, 4)
plt.plot([3, 5, 1])
plt.show()
-
- 疑问:使用figure添加子图操作,并同时设置大小??
常用图形绘制
散点图
plt.scatter()
- x, y 数据坐标点
- s 点的面积,
- c 颜色(default=蓝色),
- alpha 透明度
- marker 标记形状
- edgecolors 散点边框颜色
plt.scatter(
[1, 2, 3, 4, 2, 2, 2],
[3, 4, 1, 6, 4, 4, 4],
alpha=0.8, # 设置透明度,可以使得重合点的颜色较深,无重合点的颜色较浅,
# 一般用户检测样本密度时使用
s=50, # 点面积
c='red', # 颜色
marker='*', # 标记
edgecolors='blue' # 一般情况,边框变颜色为测试集数据
)
plt.scatter([1], [2], s=60, edgecolors='red')
plt.title('散点图演示')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
条形图
可用于样本的数值可视化
plt.bar()
常用:
- x, y 数据横纵坐标
- alpha 透明度
- color 颜色
- width 宽度,默认0.8
plt.bar(
[1, 2, 3, 4],
[2, 3, 4, 2,],
alpha=0.5,
color='red',
width=0.5 )
plt.barh() 横向条形图
plt.barh(
[1, 2, 3, 4],
[2, 3, 4, 2,],
alpha=0.5,
color='red',
height=0.5)
- 参数表
直方图
可直观显示各数据的多少,即:频数统计
plt.hist()
饼图
用户表达集合中各部分的百分比
常用于:类别分析,数据分析
plt.pie()
- label 参数设置每一块的标签
- autopct 数据显示格式(%1.1f%%)
- explode 炸裂效果,默认0, 格式[ 0, 0, 1, 1 ]
- shadow 是否有阴影,默认False