Matplotlib 库-简介与绘制子图
导入 Matplotlib 库中的 pyplot 子库
import matplotlib.pyplot as plt
使用 Figure 对象作为画布画图
figure(num,figsize,dpi,facecolor,edgecolor,frameon) num: 图形编号或名称,取值为数字/字符串 figsize:绘画对象的宽和高,单位为英寸 dpi:绘图对象的分辨率,缺省为 80 facecolor:背景颜色 edgecolor:边框颜色 frameon:表示是否显示边框
颜色 | 缩略字符 | 颜色 | 缩略字符 |
---|---|---|---|
blue | b | black | k |
green | 9 | white | W |
red | r | cyan | C |
yellow | y | magenta | m |
子图
subplot(行数,列数,子图序号)
子图序号编号规定:从左到右,从上到下。
每个 subplot 只创建一个子图
1 | plt.subplot(2,2,1) |
设置中文字体:
plt.rcParams["font.sans-serif"]="SimHei"
Mac 下可以用以下代码查看 matplotlib 可以使用的字体, 我是用 "PingFang HK" 字体。
1 | from matplotlib import font_manager |
中文字体 | 英文描述 | 中文字体 | 英文描述 |
---|---|---|---|
宋体 | SimSun | 楷体 | KaiTi |
黑体 | SimHei | 仿宋 | FangSong |
微软雅黑 | Microsoft YaHei | 隶书 | LiSu |
微软正黑体 | Microsoft JhengHei | 幼圆 | YouYuan |
恢复标准默认配置:plt.rcdefaults()
标题
添加全局标题:suptitle(标题文字)
添加子标题:title(标题文字)
suptitle 函数参数:
参数 | 说明 | 默认值 |
---|---|---|
X | 标题位置的 x 坐标 | 0.5 |
y | 标题位置的 y 坐标 | 0.98 |
color | 标题颜色 | 黑色 |
backgroundcolor | 标题背景颜色 | 12 |
fontsize | 标题的字体大小 | |
fontweight | 字体粗细 | normal |
fontstyle | 设置字体类型 | |
horizontalalignment | 标题水平对齐方式 | center |
verticalalignment | 标题的垂直对齐方式 | top |
fontsize | fontweight |
---|---|
xx-small | light |
x-small | normal |
small | medium |
medium | semibold |
large | bold |
x-large | heavy |
xx-large | black |
title() 函数参数:
参数 | 说明 | 取值 |
---|---|---|
loc | 标题位置 | left, right |
rotation | 标题文字旋转角度 | |
color | 标题颜色 | 黑色 |
fontsize | 标题的字体大小 | |
fontweight | 字体粗细 | normal |
fontstyle | 设置字体类型 | |
horizontalalignment | 标题水平对齐方式 | center |
_verticalalignment | 标题的垂直对齐方式 | top |
fontdict | 设置参数字典 |
tight_layout(rect=[left, bottom, right, top])函数 检查坐标轴标签、刻度标签、和子图标题,自动调整子图,使之填充整个绘图区域(会影响全局标题),并消除子图之间的重叠。