官方樣例:https://matplotlib.org/gallery.html
API: https://matplotlib.org/api/pyplot_summary.html
一、基本繪圖函數
1、mp.plot(水平座標數組, 垂直座標數組)
import numpy as np
import matplotlib.pyplot as mp
# example_first
x = np.arange(1,7)
y1 = 2 * x + 5
y2 = 3 * x - 7
mp.figure()
mp.plot(x, y1) # 水平座標數組, 垂直座標數組
mp.plot(x, y2) # 水平座標數組, 垂直座標數組
mp.show()
# example_second
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.plot(x, cos_y, x, sin_y) # 水平座標數組, 垂直座標數組 連續輸入
mp.show()
2、mp.plot(x,y,format_string1)
import numpy as np
import matplotlib.pyplot as mp
a=np.arange(10)
mp.plot(a, a*1.5, 'go-', a, a*2, 'b-..', a, a*5, 'r1:') # 格式字符串中的順序沒有要求
mp.show()
3、mp.plot(…, linestyle=線型, linewidth=線寬,color=顏色)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.plot(x, cos_y, linestyle='--', linewidth=6, color='dodgerblue') # 指定線性、線寬、顏色
mp.plot(x, sin_y, linestyle=':', linewidth=0.5, color='orangered') # 指定線性、線寬、顏色
mp.show()
4、mp.xlim(左邊界, 右邊界) / mp.ylim(底邊界, 頂邊界)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min(), x.max()) # 指定 左邊界和右邊界
mp.ylim(sin_y.min(), sin_y.max()) # 指定 底邊界和頂邊界
mp.plot(x, cos_y, linestyle='--', linewidth=6, color='dodgerblue')
mp.plot(x, sin_y, linestyle=':', linewidth=0.5, color='orangered')
mp.show()
5、mp.xticks(刻度位置數組, 刻度文本數組) / mp.yticks(刻度位置數組, 刻度文本數組)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4, np.pi], # 刻度位置數組
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$']) # 刻度文本數組
mp.yticks([-1, -0.5, 0.5, 1])
mp.plot(x, cos_y, linestyle='-', linewidth=2, color='dodgerblue')
mp.plot(x, sin_y, linestyle='-', linewidth=2, color='orangered')
mp.show()
5、座標軸
ax = mp.gca() # 獲取當前座標軸
ax.spines[‘left’].set_position((‘data’, 0))
ax.spines[‘left’].set_color(顏色)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca() # 獲取當前座標軸
ax.spines['left'].set_position(('data', 0)) # 設置 y 軸的位置(左邊線)
ax.spines['bottom'].set_position(('data', 0)) # 設置 x 軸的位置(下邊線)
ax.spines['right'].set_color('none') # 右邊線 清除
ax.spines['top'].set_color('none') # 上邊線 清除
mp.plot(x, cos_y, linestyle='-', linewidth=2, color='dodgerblue')
mp.plot(x, sin_y, linestyle='-', linewidth=2, color='orangered')
mp.show()
6、mp.plot(…, label=圖例文本) / mp.legend(loc=‘upper left’)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
mp.plot(x, cos_y, linestyle='-', linewidth=2, color='dodgerblue', label=r'$y=\frac{1}{2}cos(x)$') # 添加 label=圖例文本
mp.plot(x, sin_y, linestyle='-', linewidth=2, color='orangered', label=r'$y=sin(x)$') # 添加 label=圖例文本
mp.legend(loc='upper left') # 設置顯示位置
mp.show()
7、描點
mp.scatter(水平座標數組, 垂直座標數組,marker=點型, s=大小, edgecolor=勾邊色,facecolor=填充色, zorder=Z序)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
xo = np.pi * 3 / 4
yo_cos = np.cos(xo) / 2
yo_sin = np.sin(xo)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
mp.plot(x, cos_y, linestyle='-', linewidth=2, color='dodgerblue', label=r'$y=\frac{1}{2}cos(x)$')
mp.plot(x, sin_y, linestyle='-', linewidth=2, color='orangered', label=r'$y=sin(x)$')
mp.plot([xo, xo], [yo_cos, yo_sin], linestyle='--', linewidth=1, color='limegreen') # 畫線
mp.scatter([xo, xo], [yo_cos, yo_sin], s=60, edgecolor='limegreen', facecolor='white', zorder=3) # 描點
mp.legend(loc='upper left')
mp.show()
7、註釋
mp.annotate(備註文本,xy=目標位置,xycoords=目標座標系,xytext=文本位置,textcoords=文本座標系,fontsize=字體大小,arrowprops=箭頭屬性)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
xo = np.pi * 3 / 4
yo_cos = np.cos(xo) / 2
yo_sin = np.sin(xo)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
mp.plot(x, cos_y, linestyle='-', linewidth=2, color='dodgerblue', label=r'$y=\frac{1}{2}cos(x)$')
mp.plot(x, sin_y, linestyle='-', linewidth=2, color='orangered', label=r'$y=sin(x)$')
mp.plot([xo, xo], [yo_cos, yo_sin], linestyle='--', linewidth=1, color='limegreen')
mp.scatter([xo, xo], [yo_cos, yo_sin], s=60, edgecolor='limegreen', facecolor='white', zorder=3)
mp.legend(loc='upper left')
mp.annotate(
r'$\frac{1}{2}cos(\frac{3\pi}{4})=-\frac{\sqrt{2}}{4}$',
xy=(xo, yo_cos), xycoords='data',
xytext=(-90, -40), textcoords='offset points',
fontsize=14,
arrowprops=dict(arrowstyle='->',connectionstyle='arc3, rad=.2')) # 註釋
mp.annotate( # 註釋
r'$sin(\frac{3\pi}{4})=\frac{\sqrt{2}}{2}$', # 備註文本
xy=(xo, yo_sin), xycoords='data', # 目標位置, 目標座標系
xytext=(20, 20), textcoords='offset points', # 文本位置, 文本座標系
fontsize=14, # 字體大小,
arrowprops=dict(arrowstyle='->',connectionstyle='arc3, rad=.2')) # 箭頭屬性
mp.show()
二、圖形對象
1、mp.figure(圖形對象名, figsize=窗口大小,dpi=分辨率, facecolor=顏色)
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.figure('Figure Object 1', figsize=(6, 4), dpi=120, facecolor='lightgray')
mp.title('Figure Object 1', fontsize=16)
mp.xlabel('x', fontsize=12)
mp.ylabel('y', fontsize=12)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.figure('Figure Object 2', figsize=(6, 4), dpi=120, facecolor='lightgray')
mp.title('Figure Object 2', fontsize=16)
mp.xlabel('x', fontsize=12)
mp.ylabel('y', fontsize=12)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.figure('Figure Object 1')
mp.plot(x, cos_y, label=r'$y=\frac{1}{2}cos(x)$')
mp.legend()
mp.figure('Figure Object 2')
mp.plot(x, sin_y, label=r'$y=sin(x)$')
mp.legend()
mp.show()
三、子圖
1、缺省佈局
mp.subplot(行數, 列數, 圖號)
mp.subplot(2, 3, 1)
mp.subplot(231)
import matplotlib.pyplot as mp
mp.figure(facecolor='lightgray')
for i in range(2):
for j in range(3):
k = i * 3 + j + 1
mp.subplot(2, 3, k)
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, str(k), ha='center', va='center', size=36, alpha=0.5)
mp.tight_layout()
mp.show()
2、柵格佈局
import matplotlib.gridspec as mg
gs = mg.GridSpec(行數, 列數) # 柵格佈局器
mp.subplot(gs[行, 列])
import matplotlib.pyplot as mp
import matplotlib.gridspec as mg
mp.figure(facecolor='lightgray')
gs = mg.GridSpec(3, 3)
mp.subplot(gs[0, :2])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '1', ha='center', va='center', size=36, alpha=0.5)
mp.subplot(gs[1:, 0])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '2', ha='center', va='center', size=36, alpha=0.5)
mp.subplot(gs[2, 1:])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '3', ha='center', va='center', size=36, alpha=0.5)
mp.subplot(gs[:2, 2])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '4', ha='center', va='center', size=36, alpha=0.5)
mp.subplot(gs[1, 1])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '5', ha='center', va='center', size=36, alpha=0.5)
mp.tight_layout()
mp.show()
3、自由佈局
mp.axes([左下角水平座標, 左下角垂直座標, 寬度, 高度])
其中所有的尺寸參數都是相對比例。
import matplotlib.pyplot as mp
mp.figure(facecolor='lightgray')
mp.axes([0.03, 0.038, 0.94, 0.924])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '1', ha='center', va='center', size=36, alpha=0.5)
mp.axes([0.63, 0.076, 0.31, 0.308])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '2', ha='center', va='center', size=36, alpha=0.5)
mp.show()
4、座標刻度定位器
定位器對象 = mp.xxxLocator(…)
ax = mp.gca()
ax.xaxis.set_major_locator(定位器對象) # 主刻度
ax.xaxis.set_minor_locator(定位器對象) # 次刻度
import numpy as np
import matplotlib.pyplot as mp
mp.figure()
locators = [
'mp.NullLocator()',
'mp.MaxNLocator(nbins=3, steps=[1, 3, 5, 7, 9])',
'mp.FixedLocator(locs=[0, 2.5, 5, 7.5, 10])',
'mp.AutoLocator()',
'mp.IndexLocator(offset=0.5, base=1.5)',
'mp.MultipleLocator()',
'mp.LinearLocator(numticks=21)',
'mp.LogLocator(base=2, subs=[1.0])']
n_locators = len(locators)
for i, locator in enumerate(locators):
mp.subplot(n_locators, 1, i + 1) # 佈局 :n_locators行,1列
mp.xlim(0, 10) # x軸 範圍
mp.ylim(-1, 1) # y軸 範圍
mp.yticks(()) # y賦值 空
ax = mp.gca() # 獲取當前的axes繪圖區域
# 清除上、左、右邊界,保留底邊x軸
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
ax.xaxis.set_major_locator(eval(locator)) # 主刻度
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1)) # 次刻度
mp.plot(np.arange(11), np.zeros(11), c='none') # 畫線
mp.text(5, 0.3, locator[3:], ha='center', size=12) # 文本
mp.tight_layout()
mp.show()
5、散點圖
import numpy as np
import matplotlib.pyplot as mp
n = 1000
x = np.random.normal(0, 1, n) # 正態分佈數據獲取
y = np.random.normal(0, 1, n)
d = np.sqrt(x ** 2 + y ** 2)
mp.figure('Scatter', facecolor='lightgray')
mp.title('Scatter', fontsize=20)
mp.xlabel('x', fontsize=14) # x軸標籤
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.scatter(x, y, s=60, c=d, cmap='jet_r', alpha=0.5, marker='o') # 描點 c:顏色
mp.show()
6、區域填充
mp.fill_between(水平座標數組, 垂直座標起點數組, 垂直座標終點數組, 條件, color=顏色, alpha=透明度)
import numpy as np
import matplotlib.pyplot as mp
n = 1000
x = np.linspace(0, 8 * np.pi, n)
sin_y = np.sin(x)
cos_y = np.cos(x / 2) / 2
mp.figure('Fill', facecolor='lightgray')
mp.title('Fill', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.plot(x, sin_y, c='dodgerblue', label=r'$y=sin(x)$')
mp.plot(x, cos_y, c='orangered', label=r'$y=\frac{1}{2}cos(\frac{x}{2})$')
mp.fill_between(x, cos_y, sin_y, cos_y < sin_y, color='dodgerblue', alpha=0.5) # 填充
mp.fill_between(x, cos_y, sin_y, cos_y > sin_y, color='orangered', alpha=0.5) # 填充
mp.legend()
mp.show()
7、柱狀圖
mp.bar(水平座標數組, 高度數組, ec=邊緣顏色, fc=填充顏色, label=標籤文本, alpha=透明度)
import numpy as np
import matplotlib.pyplot as mp
n = 12
x = np.arange(n)
y1 = (1 - x / n) * np.random.uniform(0.5, 1.0, n) # 均勻分佈
y2 = (1 - x / n) * np.random.uniform(0.5, 1.0, n)
mp.figure('Bar', facecolor='lightgray')
mp.title('Bar', fontsize=20)
mp.ylim(-1.25, 1.25)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.xticks(x, x + 1)
mp.tick_params(labelsize=10)
mp.grid(axis='y', linestyle=':')
mp.bar(x, y1, ec='white', fc='dodgerblue', label='Sample 1') # 柱狀
for _x, _y in zip(x, y1):
mp.text(_x, _y, '%.2f' % _y, ha='center', va='bottom', size=8)
mp.bar(x, -y2, ec='white', fc='dodgerblue', alpha=0.5, label='Sample 2') # 柱狀
for _x, _y in zip(x, y2):
mp.text(_x, -_y - 0.015, '%.2f' % _y, ha='center', va='top', size=8)
mp.legend()
mp.show()
8、等高線圖
- 繪製等高線
mp.contour(x, y, z, 線數, colors=顏色, linewidths=線寬) - 等高線填充
mp.contourf(x, y, z, 線數, cmap=顏色映射)
import numpy as np
import matplotlib.pyplot as mp
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n)) # 生成網格點座標矩陣 【linspace(等差列表)】
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
mp.figure('Contour', facecolor='lightgray')
mp.title('Contour', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.contourf(x, y, z, 8, cmap='jet') # 等高線填充
cntr = mp.contour(x, y, z, 8, colors='black', linewidths=0.5) # 繪製等高線
mp.clabel(cntr, inline_spacing=1, fmt='%.1f', fontsize=10) # 標註等高線
mp.show()
9、熱像圖
mp.imshow(矩陣, cmap=顏色映射,origin=垂直軸方向)
import numpy as np
import matplotlib.pyplot as mp
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n)) # 生成網格點座標矩陣 【linspace(等差列表)】
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
mp.figure('Hot', facecolor='lightgray')
mp.title('Hot', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.imshow(z, cmap='jet', origin='low') # 熱像圖
mp.show()
10、餅圖
mp.pie(值列表, 間隙列表, 標籤, 顏色列表, 格式串,shadow=是否帶陰影, startangle=起始角度)
import matplotlib.pyplot as mp
mp.figure('Pie', facecolor='lightgray')
mp.title('Pie', fontsize=20)
mp.pie(
[26, 17, 21, 29, 11], # 值列表
[0.05, 0.01, 0.01, 0.01, 0.01], # 間隙列表
['Python', 'JavaScript', 'C++', 'C', 'PHP'], # 標籤
['dodgerblue', 'orangered', 'limegreen', 'violet', 'gold'], # 顏色列表
'%d%%', shadow=True, startangle=90) # 格式串,shadow=是否帶陰影, startangle=起始角度
mp.axis('equal') # 設置x,y軸相等
mp.show()
11、三維曲面
from mpl_toolkits.mplot3d import axes3d
ax = mp.gca(projection=‘3d’)
ax.plot_surface(x, y, z, rstride=行距,cstride=列距, cmap=顏色映射)
ax.plot_wireframe(x, y, z, rstride=行距,cstride=列距, linewidth=線寬, color=顏色)
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
mp.figure('3D Wireframe')
ax = mp.gca(projection='3d')
mp.title('3D Wireframe', fontsize=20, y=1.2) # 標題:y 修改位置
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
ax.plot_wireframe(x, y, z, rstride=30,
cstride=30, linewidth=0.5,
color='orangered') # 線曲面
mp.show()
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
mp.figure('3D Surface')
ax = mp.gca(projection='3d')
mp.title('3D Surface', fontsize=20, y=1.2) # 標題:y 修改位置
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
ax.plot_surface(x, y, z, rstride=30,
cstride=30, cmap='jet') # 面曲面
mp.show()
12、三維散點
ax.scatter(x, y, z, s=大小, c=顏色, marker=點型)
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
z = np.random.normal(0, 1, n)
d = np.sqrt(x ** 2 + y ** 2 + z ** 2)
mp.figure('Scatter3D')
ax = mp.gca(projection='3d')
mp.title('Scatter3D', fontsize=20, y=1.1)
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
ax.scatter(x, y, z, s=60, c=d, cmap='jet_r', alpha=0.5, marker='o') # 描點
mp.show()
13、極座標系
mp.gca(projection=‘polar’)
mp.plot …
mp.scatter …
x, y
| |
v v
極角 極徑
import numpy as np
import matplotlib.pyplot as mp
t = np.linspace(0, 2 * np.pi, 1001)
r_spiral = 0.8 * t
r_rose = 5 * np.sin(6 * t)
mp.figure('Polar', facecolor='lightgray')
mp.gca(projection='polar')
mp.title('Polar', fontsize=20, y=1.1)
mp.xlabel(r'$\theta$', fontsize=14)
mp.ylabel(r'$\rho$', fontsize=14, y=0.6)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.plot(t, r_spiral, c='dodgerblue', label=r'$\rho=0.8\theta$')
mp.plot(t, r_rose, c='orangered', label=r'$\rho=5sin(6\theta)$')
mp.legend()
mp.show()
14、半對數座標
mp.semilogy(…)
import numpy as np
import matplotlib.pyplot as mp
y = np.array([1, 10, 100, 1000, 100, 10, 1])
mp.figure('Normal & Log', facecolor='lightgray')
mp.subplot(211)
mp.title('Normal', fontsize=16)
mp.ylabel('y', fontsize=12)
ax = mp.gca()
ax.xaxis.set_major_locator(mp.MultipleLocator(1))
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))
ax.yaxis.set_major_locator(mp.MultipleLocator(250))
ax.yaxis.set_minor_locator(mp.MultipleLocator(50))
mp.tick_params(labelsize=10)
mp.grid(which='major', axis='both',linewidth=0.75, linestyle='-',color='lightgray')
mp.grid(which='minor', axis='both',linewidth=0.25, linestyle='-',color='lightgray')
mp.plot(y, 'o-', c='dodgerblue', label='plot')
mp.legend()
mp.subplot(212)
mp.title('Log', fontsize=16)
mp.xlabel('x', fontsize=12)
mp.ylabel('y', fontsize=12)
ax = mp.gca()
ax.xaxis.set_major_locator(mp.MultipleLocator(1))
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))
mp.tick_params(labelsize=10)
mp.grid(which='major', axis='both',linewidth=0.75, linestyle='-',color='lightgray')
mp.grid(which='minor', axis='both',linewidth=0.25, linestyle='-',color='lightgray')
mp.semilogy(y, 'o-', c='orangered',label='semilog') # 半對數
mp.legend()
mp.tight_layout()
mp.show()
15、簡單動畫
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
n_bubbles = 100
bubbles = np.zeros(n_bubbles, dtype=[('position', float, 2),('size', float, 1),('growth', float, 1),('color', float, 4)]) # 初始化 100個點
bubbles['position'] = np.random.uniform(0, 1, (n_bubbles, 2)) # 均勻分佈 位置:2個數值
bubbles['size'] = np.random.uniform(50, 750, n_bubbles) # 均勻分佈 大小:1個數值
bubbles['growth'] = np.random.uniform(30, 150, n_bubbles) # 均勻分佈 成長速度:1個數值
bubbles['color'] = np.random.uniform(0, 1, (n_bubbles, 4)) # 均勻分佈 顏色:4個數值
mp.figure('Bubbles', facecolor='lightgray')
mp.title('Bubbles', fontsize=20)
mp.xticks(())
mp.yticks(())
sc = mp.scatter(bubbles['position'][:, 0],bubbles['position'][:, 1],s=bubbles['size'],c=bubbles['color']) # 描點:位置,大小,顏色
def update(number):
bubbles['size'] += bubbles['growth']
burst = number % n_bubbles
bubbles['position'][burst] = np.random.uniform(0, 1, 2)
bubbles['size'][burst] = 0
bubbles['growth'][burst] = np.random.uniform(30, 150)
bubbles['color'][burst] = np.random.uniform(0, 1, 4)
sc.set_offsets(bubbles['position'])
sc.set_sizes(bubbles['size'])
sc.set_facecolor(bubbles['color'])
anim = ma.FuncAnimation(mp.gcf(), update, interval=10)
mp.show()
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
mp.figure('Signal', facecolor='lightgray')
mp.title('Signal', fontsize=20)
mp.xlabel('Time', fontsize=14)
mp.ylabel('Signal', fontsize=14)
ax = mp.gca()
ax.set_ylim(-3, 3)
ax.set_xlim(0, 10)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
pl = mp.plot([], [], c='orangered')[0]
pl.set_data([], [])
def update(data):
t, v = data
x, y = pl.get_data()
x.append(t)
y.append(v)
x_min, x_max = ax.get_xlim()
if t >= x_max:
ax.set_xlim(t - (x_max - x_min), t)
ax.figure.canvas.draw()
pl.set_data(x, y)
def generator():
t = 0
while True:
v = np.sin(2 * np.pi * t) * np.exp(np.sin(0.2 * np.pi * t))
yield t, v
t += 0.05
anim = ma.FuncAnimation(mp.gcf(), update, generator, interval=5)
mp.show()
附錄1:format_string
format_string:控制曲線的格式字符串,可選(由顏色字符、風格字符和標記字符組成),參見附錄1 ↩︎