介紹
本文不是一篇詳盡的、從簡到繁的 Maplotlib 畫圖教程,而是用各種例子快速直觀地讓讀者上手 Matplotlib 畫圖中的一些常用的、基礎的操作。本文不對各種數據圖(折線圖、柱狀圖等)作介紹。文中配有效果示意圖及代碼。本文亦可作常用畫圖函數/參數查詢之用。
寫在前面
什麼樣的數據圖纔是好的?
圖之好壞不在繁簡,一副好圖,應該讓讀者能清晰明瞭地理解你想要表達的意思。所以在設計圖的時候,此爲第一要義。
檢查你的數據圖
- 是否對色盲友好?(避免過多地使用紅綠配色。)
- 如果打印成黑白稿(grayscale)的話,讀者是否還能分辨出不同的元素?(避免僅使用顏色來區分元素,使用恰當、對比度高的顏色,以及 Marker、線的樣式、粗細等)
- 圖片的質量是否足夠高?(PDF、EPS 等矢量圖、分辨率高的 PNG、JPG )
- 標題、標籤、刻度、圖例是否正確,表達清楚?(最好不要僅使用數學符號來表示軸標籤,例如 、 等,使用明確的文字來描述。)
- 使用的字體與正文是否一致?
基礎知識
在介紹其他內容之前,我們先回顧一下基礎知識,這裏借用 Matplotlib 文檔的一張圖 [1]:
圖中共標出了14種概念:
- Figure - 畫板
- Title - 標題
- X axis label - X軸標籤
- Y axis label - Y軸標籤
- Legend - 圖例
- Major tick label - 主刻度標籤
- Minor tick label - 次刻度標籤
- Grid - 網格
- Line (line plot) - 線
- Markers (scatter plot) - 標記
- Major tick - 主刻度
- Minor tick - 次刻度
- Axes - 軸
- Spines - 脊
這些基礎概念十分有用,希望大家能記住其作用及對應的英文。如果遇到更復雜的需求,可以直接在官網文檔中進行查詢。
環境
- Python 3.7.3
- Matplotlib 3.1.3
常用鏈接
顏色 Colors:
- Choosing Colormaps in Matplotlib - List of Named Colors - HTML Color Picker - Color Brewer 2.0 - How to find a color scheme that’s also useful when printed in black and white?
線樣式:
標記樣式:
刻度:
圖例:Legend Guide
正文
開始畫圖
import matplotlib.pyplot as plt # 之後的代碼默認引入此包
Figure 畫板
創建一個簡單的畫板並展示
fig, ax = plt.subplots()
plt.show() # 之後的代碼默認省略此步驟
設定畫板的長寬figsize
fig, ax = plt.subplots(figsize=(12, 3))
設定子圖
fig , ax = plt.subplots(nrows=3, ncols=5)
nrows
和ncols
參數分別爲行數和列數。更復雜的例子請參考官網教程。
訪問不同的字圖
假設現在有三行五列:
ax[0, 4].plot(x, y, color='limegreen')
ax[2, 2].plot(x, y, color='red')
緊湊佈局 Tight Layout
fig, ax = plt.subplots(tight_layout=True)
畫板背景色
ax.set_facecolor('lightblue')
圖中圖 Inset
ax.plot(x, y, color='limegreen', label='Xovee')
inset = plt.axes((.5, .5, .3, .3), facecolor='lightblue')
inset.plot(x, y, color='red')
標籤 Label
設定圖片的軸標籤、標題、字體顏色、字體大小
plt.title()
plt.xlabel()
、plt.ylabel()
plt.set_title()
ax.set_xlabel()
、ax.set_ylabel()
ax.set_title("Xovee's Figure", fontsize=24, color='red')
ax.set_xlabel('Xovee', fontsize=20, color='lightblue')
ax.set_ylabel('Xovee', fontsize=20, color='coral')
軸 Axes/Axis
設定軸的範圍
ax.set_xlim(np.pi, 3*np.pi)
ax.set_ylim(-.5, .5)
設定軸的縮放 Scale
可選項包括:
linear
默認log
symlog
logit
fig, ax = plt.subplots(ncols=2, figsize=(8, 4), tight_layout=True)
x = np.linspace(0, 100, 1000)
y = [2**x_ for x_ in x]
ax[0].plot(x, y, color='limegreen', label='Xovee')
ax[1].plot(x, y, color='coral')
ax[1].set_yscale('log')
設定軸的上下界、粗細、顏色
ax.plot(x, y, color='limegreen', label='Xovee')
ax.set_yticks([-.5, 0., .5])
ax.set_xticks([2, 4, 6, 8])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_bounds(-.5, .5)
ax.spines['bottom'].set_bounds(2, 8)
ax.spines['bottom'].set_linewidth(2)
ax.spines['bottom'].set_color('red')
隱藏軸
hide_axes = ['left', 'top', 'right', 'bottom']
for axis in hide_axes:
ax.spines[axis].set_visible(False)
讀者可以關注一下這個ax.spines
,即軸的脊椎,將其可見度設爲False
:
設定右(上)座標軸
ax.twinx()
,同理可以設置上座標軸ax.twiny()
。
ax.plot(x, y, color='limegreen', label='Xovee')
axr = ax.twinx()
axr.set_yticks([.5])
axr.set_yticklabels(['Xovee'])
Tick 刻度
設置刻度的長、寬、顏色
# axis 默認是 both, 或者 x 和 y
# which 可以是 major, minor, both
ax.tick_params(axis='both', which='major', color='blue', length=10, width=3)
自定義刻度的位置和標籤
plt.xticks()
、plt.yticks()
ax.set_xticks()
和ax.set_xticklabels()
ax.set_yticks()
和ax.set_yticklabels()
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(tight_layout=True)
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
plt.plot(x, y, color='limegreen', label='Xovee')
plt.xticks([0, np.pi, 2*np.pi, 3*np.pi, 12], ['0.0', '$\pi$', '$2\pi$', '3$\pi$', '12'], fontsize=16, rotation=30, color='red')
plt.yticks([-1, 0, 1], fontsize=16, color='blue')
plt.show()
顯示(隱藏)主/次刻度
右軸顯示minor
次刻度,下軸不顯示minor
次刻度。
ax.set_xticks([1e1, 1e2, 1e4], minor=True)
ax.set_yticks([1e-4, 1e-2, 1e0], minor=False)
Legend 圖例
設定圖例位置和文字大小
loc
的可選參數包括best
, lower
, upper
, center
, left
, right
及其部分組合例如lower left
。
plt.legend(loc='lower center', fontsize=24)
設定圖例位置
bbox_to_anchor
參數的四元組,以左下角爲參照,設定圖例的位置:
plt.legend(loc='lower left', bbox_to_anchor=(0, 1.05, .5, 1.05), fontsize=24)
多行多列圖例、圖例背景顏色
legend = plt.legend(loc='lower left', ncol=3, fontsize=16)
legend.get_frame().set_facecolor('linen')
網格 Grid
fig, ax = plt.subplots(ncols=3, tight_layout=True)
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
ax[0].plot(x, y, color='limegreen', label='Xovee')
ax[1].plot(x, y, color='red', label='Xovee')
ax[2].plot(x, y, color='blue', label='Xovee')
ax[0].grid(axis='x', linestyle='--')
ax[1].grid(axis='y', linewidth=5)
ax[2].grid(color='purple')
其他命令
減小生成的文件大小
添加rasterized=True
參數。
plt.plot(x, y, rasterized=True)
plt.scatter(x, y, rasterized=True)
...
文字 Text
ax.text(2, 0, 'Xovee Xu is watching you!!!', fontsize=12, weight='bold', color='Coral')
設定字體
from matplotlib import rcParams
rcParams['font.family'] = 'Times New Roman'
使用 TrueType 字體(或避免 Type 3 字體)
第一種方法是更改配置文件,即默認之後所有的畫圖都使用 TrueType 字體:
- 首先找到並修改
matplotlib
文件 - 如果你不知道該文件的位置,在 python 中輸入以下命令 [2]
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/home/foo/.config/matplotlib/matplotlibrc'
- 修改以下兩項即可 [3]
pdf.fonttype : 42
ps.fonttype : 42
第二種方法是在單個畫圖代碼中使用如下命令:
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
設定層級 zorder
zorder
高的元素顯示在zorder
低低元素之上。
ax[0].scatter([0], [2], s=1e5)
ax[0].scatter([0], [0], s=1e5, c='red')
ax[1].scatter([0], [2], s=1e5, zorder=5)
ax[1].scatter([0], [0], s=1e5, c='red', zorder=3)
透明 alpha
設定alpha
參數,1
爲不透明,0
爲完全透明。
ax.scatter([0], [2], s=1e5, c='green', alpha=.5)
ax.scatter([0], [0], s=1e5, c='yellow', alpha=.5)
ax.scatter([-1], [1], s=3e4, c='red', zorder=0)
ax.scatter([1], [1], s=3e4, c='blue', alpha=1.)
設置顏色地圖:例一 colormap
各種colormap
顏色參考值可以在這裏找到。
fig, ax = plt.subplots(tight_layout=True)
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
cmp = plt.cm.get_cmap('rainbow')
for i in range(len(x)-1):
plt.plot([x[i], x[i+1]], [y[i], y[i+1]], linewidth=5, color=cmp(x[i]/max(x)))
設置顏色地圖:例二 colormap
ax.scatter(x, y, s=x**2, c=y, cmap='rainbow')
打印出系統中支持的字體名
import matplotlib.font_manager
a = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
print(i)
Reference
- Usage Guide. (Mar 20, 2020). Retrieved from https://matplotlib.org/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-py
- Customizing Matplotlib with style sheets and rcParams. (Apr 8, 2020). Retrieved from https://matplotlib.org/tutorials/introductory/customizing.html
- Jamie Oaks. (Mar 1, 2014). Avoiding Type 3 fonts in matplotlib plots. Retrieved from http://phyletica.org/matplotlib-fonts/