Matplotlib 是 Python 最流行的 2D 繪圖庫,提供類 MATLAB 的 pyplot 介面。本文涵蓋基本繪圖流程、線條樣式、多圖疊加、柱狀圖、子圖佈局、文字標註與圖例配置。
import matplotlib.pyplot as plt
plt.figure(figsize=(8,4))
plt.plot([1,2,3,4]) # y 值,x 自動 0..3
plt.ylabel('some numbers')
plt.title('hello')
plt.show()
x = [0,1,2,4,5,6]
y = [1,2,3,2,4,1]
plt.plot(x, y, '-*r') # 格式字串: 線型-標記-顏色
plt.xlabel('x-axis'); plt.ylabel('y-axis')
plt.show()
常用格式字元:- 實線、-- 虛線、: 點線、-. 虛點線;o 圓點、* 星號、+ 加號;r 紅、g 綠、b 藍、k 黑。
z = [1,2,3,4,5,6]
plt.plot(x, y, '--*r', x, z, '-.+g')
plt.legend(['Line Y', 'Line Z'])
plt.show()
plt.bar(x, y)
plt.show()
plt.figure(1)
plt.subplot(2,1,1) # 2 行 1 列 第 1 個
plt.plot(x, y, '-+b')
plt.subplot(2,1,2) # 第 2 個
plt.plot(x, z, '-.*r')
plt.show()
plt.text(1, 2, "I'm a text") # (x, y, 文字)
plt.show()
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
line, = plt.plot([1,2,3])
line.set_label("Label via method")
plt.legend()
line1, = plt.plot([1,2,3])
line2, = plt.plot([3,2,1], '--b')
plt.legend((line1, line2), ('line1', 'line2'))