导入Matplotlib

约定俗成的以 plt 为 Matplotlib 简称的导入方式

1
import matplotlib.pyplot as plt

魔法配置,让表格显示在 jupyter 里面

1
%matplotlib notebook

中文字体支持配置

第一种方法

  1. 打印所有系统字体
1
2
for i in sorted([f.name for f in mpl.font_manager.fontManager.ttflist]):
print(i)
  1. 找到一个可以显示中文的字体
1
2
3
# 比如我使用的 Songti SC
# 将其设置为当前字体
plt.rcParams['font.family']=['Songti SC']

第二种方法

  1. 找到自定义字体文件夹
1
font_dirs = ['/Users/askeynil/Desktop/学习/numpy/fonts']
  1. 将自定义字体文件夹导入到 Matplotlib 的字体库中
1
2
3
4
5
import matplotlib.font_manager as font_manager
font_dirs = ['/Users/askeynil/Desktop/学习/numpy/fonts']
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
font_list = font_manager.createFontList(font_files)
font_manager.fontManager.ttflist.extend(font_list)
  1. 然后使用方式一找到导入的字体,然后设置为 family 即可。

绘制折线图

  1. 创建一个图形实例
1
fig = plt.figure()
  1. 获取 y 值,x 值默认从 0 开始,依次累加 1
1
plt.plot([2, 3, 1, 4])
  1. 设置 x,y 轴标签
1
2
plt.xlabel('x') #x轴标签
plt.ylabel('y') #y轴标签
  1. 绘制图形
1
plt.show()

指定绘制图形的大小

1
fig = plt.figure(figsize=(5, 4), dpi=80)

参数解释:

  1. figsize:图形尺寸,英寸为单位

  2. dpi:每英寸的点数

绘制三角函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 1. 导入 numpy
import numpy as np
# 2. 获取 x 轴的值
x = np.linspace(-np.pi, np.pi, 100) # -pi 到 pi 中 100 个点
# 3. 获取 cos 函数的 y 值
c = np.cos(x)
# 4. 获取 sin 函数的 y 值
s = np.sin(x)
# 5. 获取绘图实例
fig = plt.figure()
# 6. 绘制 cos 的图形
plt.plot(x, c)
# 7. 绘制 sin 的图形
plt.plot(x, s)
# 8. 显示图形
fig.show()

指定线宽和颜色

1
2
3
4
fig = plt.figure()
plt.plot(x, c, color='red', linewidth=2, linestyle='--')
plt.plot(x, s, color='blue', linewidth=3, linestyle='-')
fig.show()

参数解释:

  1. color:线的颜色,可以是 RGB16 进制的数值,也可以是一些默认的预定义颜色字符串
  2. linewidth:线宽
  3. linestyle:线的形状
    • ‘-‘ 或 ‘solid’:实线
    • ‘–’ 或 ‘dashed’:短划线
    • ‘-.’ 或 ‘dashdot’:点虚线
    • ‘:’ 或 ‘dotted’:虚线

指定 x 和 y 轴的范围和标签的内容

1
2
3
4
5
6
7
8
9
10
fig = plt.figure()
plt.plot(x, c, color='red')
plt.plot(x, s, color='blue')
plt.xlim(-4, 4) # 指定 x 轴的范围
plt.ylim(-1.1, 1.1) # 指定 y 轴的范围
# 设置 x 轴的标签内容
plt.xticks(np.linspace(-4, 4, 9, endpoint=True))
# 设置 y 轴的标签内容
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
fig.show()

内联 LaTeX 表达式

1
2
3
4
5
6
7
8
9
10
11
fig = plt.figure()
plt.plot(x, c, color='red')
plt.plot(x, s, color='blue')
plt.xlim(-4, 4) # 指定 x 轴的范围
plt.ylim(-1.1, 1.1) # 指定 y 轴的范围
# 设置 x 轴的标签内容
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',r'$\frac{\pi}{2}$', r'$\pi$'])
# 字符串前面加 r 表示使用原始字符串,不转义。
# 设置 y 轴的标签内容
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
fig.show()

修改坐标轴的位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fig = plt.figure()
plt.plot(x, c, color='red')
plt.plot(x, s, color='blue')
plt.xlim(-4, 4) # 指定 x 轴的范围
plt.ylim(-1.1, 1.1) # 指定 y 轴的范围
# 设置 x 轴的标签内容
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',r'$\frac{\pi}{2}$', r'$\pi$'])
# 字符串前面加 r 表示使用原始字符串,不转义。
# 设置 y 轴的标签内容
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
# 获取当前的坐标轴 gca == get current axes
axes = plt.gca()
# 设置右坐标轴颜色为 none 即隐藏右坐标轴
axes.spines['right'].set_color('none')
# 设置上坐标轴颜色为 none 即隐藏上坐标轴
axes.spines['top'].set_color('none')
# 将左坐标轴移动到原点
axes.spines['left'].set_position(('data', 0))
# 将下坐标轴移动到原点
axes.spines['bottom'].set_position(('data', 0))
fig.show()

添加函数描述

1
2
3
4
5
fig = plt.figure()
plt.plot(x, c, color='red', label='cos')
plt.plot(x, s, color='blue', label='sin')
plt.legend(loc='upper left') # Add the legend
fig.show()

参数解释:

  1. label:函数的描述
  2. plt.legend:
    1. loc:位置
      1. ‘best’:最好的
      2. ‘upper right’:右上
      3. ‘upper left’:左上
      4. ‘lower left’:左下
      5. ‘lower right’:右下
      6. ‘right’:右
      7. ‘center left’:中左
      8. ‘center right’:中右
      9. ‘lower center’:下中
      10. ‘upper center’:上中
      11. ‘center’:中心

添加关键点标注

1
2
3
4
5
6
7
8
9
fig = plt.figure()
plt.plot([2, 3, 1, 4])
plt.xlabel('x')
plt.ylabel('y')
plt.annotate('转折点',
xy=(1, 3), xytext=(+10, +30),
textcoords='offset points', fontsize=12,
arrowprops=dict(arrowstyle="->"))
fig.show()

plt.annotate

参数解释:

  1. s:显示的文本
  2. xy:标注点
  3. xytext:放置文本的位置,默认为 xy
  4. textcoords:文本点的描述
  5. fontsize:字体大小
  6. arrowprops:箭头参数,dict

绘制多图

  1. 准备表格数据
1
2
3
X = np.linspace(-np.pi, np.pi, 15)
C = np.cos(X)
S = np.sin(X)
  1. 绘制两个表格
1
2
3
4
5
6
fig = plt.figure()
plt.subplot(2, 1, 1)
plt.plot(X, C)
plt.subplot(2, 1, 2)
plt.plot(X, S)
plt.show()
  1. 设置网格
1
2
3
4
5
6
7
8
fig = plt.figure(figsize=(5, 4), dpi=80)
plt.subplot(1, 2, 1)
plt.plot(X, C)
plt.grid(False)
plt.subplot(1, 2, 2)
plt.plot(X, S)
plt.grid(True)
plt.show()

参数解释:

  1. subplot(nrows, ncols, index, **kwargs)

    1. nrows:行数
    2. ncols:列数
    3. index:索引
    4. kwargs:可选参数
  2. subplot(pos, **kwargs)

    1. pos:100 <= pos <= 999
      1. 第一个数字代表行
      2. 第二个数字代表列
      3. 第三个数字代表索引
  3. subplot(ax)

    1. ax:axes,之前 subplot 返回的值,在同一图内,再次绘制。
  4. grid()

    • 表格的配置信息

格子布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 导入布局头文件
import matplotlib.gridspec as gridspec
fig = plt.figure()
# 创建布局管理器
gs = gridspec.GridSpec(3, 3)
# 绘制在 第 0 行所有列
ax1 = plt.subplot(gs[0, :])
plt.plot(X, C)
# 绘制在第 1 行前两列
ax2 = plt.subplot(gs[1, :-1])
plt.plot(X, S)
# 绘制在最后一行,第 0 列
ax3 = plt.subplot(gs[-1, 0])
plt.plot(X, -C)
# 绘制在最后一行,第 1 列
ax4 = plt.subplot(gs[-1, -2])
plt.plot(X, -S)
# 绘制在第 1,2 行,最后一列
ax5 = plt.subplot(gs[1:, -1])
plt.plot(X, (C+S)/2)
plt.show()

评论

来发评论吧~
Powered By Valine
v1.4.14