本文采編自寒小陽老師的課程講義
一幅可視化圖的基本結構
通常,使用 numpy 組織數據, 使用 matplotlib API 進行數據圖像繪制。 一幅數據圖基本上包括如下結構:
-
Data: 數據區,包括數據點、描繪形狀
-
Axis: 坐標軸,包括 X 軸、 Y 軸及其標簽、刻度尺及其標簽
-
Title: 標題,數據圖的描述
-
Legend: 圖例,區分圖中包含的多種曲線或不同分類的數據
其他的還有圖形文本 (Text)、注解 (Annotate)等其他描述
畫法
下面以常規圖為例,詳細記錄作圖流程及技巧。按照繪圖結構,可將數據圖的繪制分為如下幾個步驟:
-
導入 matplotlib 包相關工具包
-
準備數據,numpy 數組存儲
-
繪制原始曲線
-
配置標題、坐標軸、刻度、圖例
-
添加文字說明、注解
-
顯示、保存繪圖結果
下面是一個包含cos、sin、sqrt函數的完整圖像:
#coding:utf-8
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
準備數據
x = np.arange(0., 10, 0.2)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.sqrt(x)
繪制基本曲線
使用 plot 函數直接繪制上述函數曲線,可以通過配置 plot 函數參數調整曲線的樣式、粗細、顏色、標記等:
這里r'$$'之間夾的是math公式 語法是latex
plt.plot(x, y1, color='blue', linewidth=1.5, linestyle='-', marker='.', label=r'$y = cos{x}$')
plt.plot(x, y2, color='green', linewidth=1.5, linestyle='-', marker='*', label=r'$y = sin{x}$')
plt.plot(x, y3, color='m', linewidth=1.5, linestyle='-', marker='x', label=r'$y = \sqrt{x}$')
關于顏色的補充
主要是color參數:
-
r 紅色
-
g 綠色
-
b 藍色
-
c cyan
-
m 紫色
-
y 土黃色
-
k 黑色
-
w 白色
linestyle 參數
marker 參數
marker參數設定在曲線上標記的特殊符號,以區分不同的線段。常見的形狀及表示符號如下圖所示:
設置坐標軸
可通過如下代碼,移動坐標軸 spines
ax = plt.subplot(111)#設置為1張圖
ax.spines['right'].set_color('none') # 右邊邊框顏色為白色 其實就相當于去掉邊框
ax.spines['top'].set_color('none') # 左邊邊框顏色為白色
# 移動下邊邊框線,相當于移動 X 軸
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
# 移動左邊邊框線,相當于移動 y 軸
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
可通過如下代碼,設置刻度尺間隔 lim、刻度標簽 ticks
# 設置 x, y 軸的刻度取值范圍
plt.xlim(x.min()*1.1, x.max()*1.1)
plt.ylim(-1.5, 4.0)
# 設置 x, y 軸的刻度標簽值
plt.xticks([2, 4, 6, 8, 10], [r'2', r'4', r'6', r'8', r'10'])
plt.yticks([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0],
[r'-1.0', r'0.0', r'1.0', r'2.0', r'3.0', r'4.0'])
可通過如下代碼,設置 X、Y 坐標軸和標題:
# 設置標題、x軸、y軸
plt.title(r'$the \ function \ figure \ of \ cos(), \ sin() \ and \ sqrt()$', fontsize=19)
plt.xlabel(r'$the \ input \ value \ of \ x$', fontsize=18, labelpad=88.8)
plt.ylabel(r'$y = f(x)$', fontsize=18, labelpad=12.5)
設置文字描述、注解
可通過如下代碼,在數據圖中添加文字描述 text:
plt.text(0.5, 0.7, r'$x \in [0.0, \ 10.0]$', color='k', fontsize=15)
plt.text(0.5, 0.6, r'$y \in [-1.0, \ 4.0]$', color='k', fontsize=15))
可通過如下代碼,在數據圖中給特殊點添加注解 annotate:
# 特殊點添加注解
plt.scatter([8,],[np.sqrt(8),], 50, color ='m') # 使用散點圖放大當前點
plt.annotate(r'$2\sqrt{2}$', xy=(8, np.sqrt(8)), xytext=(8.5, 2.2), fontsize=16, color='#090909', arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.1', color='#090909'))
設置圖例
可使用如下兩種方式,給繪圖設置圖例:
-
1: 在 plt.plot 函數中添加 label 參數后,使用 plt.legend(loc=’up right’)
-
2: 不使用參數 label, 直接使用如下命令:
plt.legend(['cos(x)', 'sin(x)', 'sqrt(x)'], loc='upper right')
網格線開關
可使用如下代碼,給繪圖設置網格線:
# 顯示網格線
plt.grid(True)
顯示與圖像保存
plt.show() # 顯示
# savefig('../figures/plot3d_ex.png',dpi=48) # 保存,前提目錄存在
完整的繪制程序
#coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
%matplotlib inline
import matplotlib
matplotlib.rc('figure', figsize = (20, 15))
# 定義數據部分
x = np.arange(0., 10, 0.2)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.sqrt(x)
# 繪制 3 條函數曲線
plt.plot(x, y1, color='blue', linewidth=1.5, linestyle='-', marker='.', label=r'$y = cos{x}$')
plt.plot(x, y2, color='green', linewidth=1.5, linestyle='-', marker='*', label=r'$y = sin{x}$')
plt.plot(x, y3, color='m', linewidth=1.5, linestyle='-', marker='x', label=r'$y = \sqrt{x}$')
# 坐標軸上移
ax = plt.subplot(111)
ax.spines['right'].set_color('none') # 去掉右邊的邊框線
ax.spines['top'].set_color('none') # 去掉上邊的邊框線
# 移動下邊邊框線,相當于移動 X 軸
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
# 移動左邊邊框線,相當于移動 y 軸
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 設置 x, y 軸的取值范圍
plt.xlim(x.min()*1.1, x.max()*1.1)
plt.ylim(-1.5, 4.0)
# 設置 x, y 軸的刻度值
plt.xticks([2, 4, 6, 8, 10], [r'2', r'4', r'6', r'8', r'10'])
plt.yticks([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0],
[r'-1.0', r'0.0', r'1.0', r'2.0', r'3.0', r'4.0'])
# 添加文字
plt.text(11, 1.9, r'$x \in [0.0, \ 10.0]$', color='k', fontsize=15)
plt.text(11, 1.4, r'$y \in [-1.0, \ 4.0]$', color='k', fontsize=15)
# 特殊點添加注解
plt.scatter([8,],[np.sqrt(8),], 50, color ='m') # 使用散點圖放大當前點
plt.annotate(r'$2\sqrt{2}$', xy=(8, np.sqrt(8)), xytext=(8.5, 2.2), fontsize=16, color='#090909', arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.1', color='#090909'))
# 設置標題、x軸、y軸
plt.title(r'$the \ function \ figure \ of \ cos(), \ sin() \ and \ sqrt()$', fontsize=19)
plt.xlabel(r'$the \ input \ value \ of \ x$', fontsize=18, labelpad=88.8)
plt.ylabel(r'$y = f(x)$', fontsize=18, labelpad=12.5)
# 設置圖例及位置
plt.legend(loc='upper left')
# plt.legend(['cos(x)', 'sin(x)', 'sqrt(x)'], loc='up right')
# 顯示網格線
plt.grid(True)
# 顯示繪圖
plt