
Matplotlib 是一个 Python 绘图库,可以跨平台生成各种硬拷贝格式和交互式环境的出版品质数据。
![]()
绘图解剖(Plot Anatomy)
工作流程(Workflow)
使用 matplotlib 创建绘图的基本步骤
1  | import matplotlib.pyplot as plt  | 
准备数据
1D数据
1  | import numpy as np  | 
2D数据 或 图像
1  | from matplotlib.cbook import get_sample_data  | 
创建图
1  | import matplotlib.pyplot as plt  | 
图形(Figure)
1  | fig = plt.figure()  | 
1  | fig2 = plt.figure(figsize=plt.figaspect(2.0))  | 
轴(Axes)
所有绘图都是针对 Axes 完成的。 在大多数情况下,子图符合您的需求。子图是网格系统上的轴。
1  | fig.add_axes()  | 
1  | ax1 = fig.add_subplot(221) # 行-列-数字  | 
1  | ax3 = fig.add_subplot(212)  | 
1  | fig3, axes = plt.subplots(nrows=2, ncols=2)  | 

1  | fig4, axes2 = plt.subplots(ncols=3)  | 

常规绘制
1D 数据
1  | fig, ax = plt.subplots()  | 

2D数据 或 图像
1  | fig, ax = plt.subplots()  | 

1  | # 二维数组的伪彩色图  | 

向量字段
1  | # 向轴添加箭头  | 
数据分布
1  | # 绘制直方图  | 
自定义绘图
颜色,彩条(Color bars)和彩图(Color maps)
1  | plt.plot(x, x, x, x**2, x, x**3)  | 

标记
1  | fig, ax = plt.subplots()  | 

线条样式
1  | plt.plot(x, y, linewidth=4.0)  | 

1  | plt.plot(x, y, ls='solid')  | 

1  | plt.plot(x, y, ls='--')  | 

1  | plt.plot(x, y, '--', x**2, y**2, '-.')  | 

1  | plt.setp(lines, color='r', linewidth=4.0)  | 
文字 & 注释
1  | ax.text(1,  | 
1  | ax.annotate("Sine",  | 
数学
1  | plt.title(r'$sigma_i=15$', fontsize=20)  | 

限制,图例 & 布局(Limits, Legends & Layouts)
限制 & 自动缩放(Limits & Autoscaling)
1  | ax.margins(x=0.0, y=0.1)  | 
图例
1  | # 设置标题和x轴和y轴标签  | 
1  | # 不重叠的图元素  | 
刻度(Ticks)
1  | # 手动设置 x-ticks  | 
1  | # y-ticks 变长  | 
子图间距
1  | # 调整子图之间的间距  | 
1  | # 子图适配图区域  | 
坐标轴(Axis Spines)
1  | # 向下移动底部轴线  | 
1  | # 使图的顶轴不可见  | 
保存图
保存图片(Save figures)
1  | plt.savefig('bar.png')  | 
保存透明图(Save transparent figures)
1  | plt.savefig('bar_trans.png', transparent=True)  | 
显示图
1  | plt.show()  | 
关闭 & 清除
1  | # 清除轴  | 
示例
折线图(Line plot)
1  | import matplotlib.pyplot as plt  | 

直方图( Histogram)
1  | import matplotlib.pyplot as plt  | 

散点图(Scatter plot)
1  | import matplotlib.pyplot as plt  | 

3D 图(3D plot)
1  | from matplotlib import cm  | 

在线预览
https://github.com/iOSDevLog/AIDevLog/blob/master/Python%20%E5%9F%BA%E7%A1%80/MatplotlibBasic.ipynb