Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers, and four graphical user interface toolkits.
Matplotlib介绍
Matplotlib 是 python 的绘图库。一副完整的图形(figure)包括标题(title)、坐标轴标题(X&Y axis label)、边框线(spines)、主要刻度线(major tick)、主要刻度线标题(major tick label)、次要刻度线(minor tick)、次要刻度线标题(minor tick label)、图例(legend)、网格线(grid)、线(line)以及标记(marker)等,如下图所示。
简单例子
一个简单的例子,使用 pandas 从 Excel 中读取数据,画折线图。值得注意的是,安装完 pandas 需要 pip install xlrd
,否则会报错:ImportError: No module named ‘xlrd’。
1 | # -*- coding: utf-8 -*- |
复杂例子
折线图
上个例子比较简单,matplotlib 提供了许多 API 来自定义 figure 的各种设置。
调整边框线的粗细需要同时调整图例和刻度线,即:
1 | width = 1 |
1 | # -*- coding: utf-8 -*- |
柱状图
柱状图相对复杂些,需要设置每个柱体的宽度。
另外,可以设置每个主要刻度线的标记(tick)。
1 | # -*- coding: utf-8 -*- |
subplot
使用 matplotlib 可以很方便的绘制子图。abc
代表 a 行 b 列第 c 个图,顺序从左到右,从上往下。
1 | # a为横坐标值,b、c、d、e为纵坐标值 |
当第一行有两个子图,第二行只有一个的时候,需要使用 GridSpec。
1 | gs = gridspec.GridSpec(2, 4) |
双坐标轴
使用 twinx() 方法,共享横坐标轴。
1 | fig, ax1 = plt.subplots() |
字体
默认情况下,matplotlib 不支持中文,解决办法参考知乎的讨论。但对一些强迫症来说,中文要是宋体或黑体,英文必须是 Times New Roman。一种完美的解决方案是使用 LaTeX 渲染,不过图片生成的时间比较长。
使用 LaTeX 渲染,需要安装 LaTeX 和 Ghostscript,否则一直会报错:FileNotFoundError: [WinError 2] 系统找不到指定的文件。参见官网的使用指南 Text rendering With LaTeX。
Windows 版本的 Protext 可以从 清华大学开源软件镜像站下载,但一定记住下载 protext.exe
这个文件,那个带版本号的文件有问题,安装不了。
1 | # -*- coding: utf-8 -*- |
Perfect!