基本用法
使用內建的顏色對映非常簡單,只需將所需顏色對映的名稱(如 colormaps 參考中所示 )傳遞給期望它的繪圖函式(例如 pcolormesh
或 contourf
),通常採用 cmap
關鍵字引數的形式:
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.pcolormesh(np.random.rand(20,20),cmap='hot')
plt.show()
色彩圖對於在二維圖上視覺化三維資料特別有用,但是一個好的色圖也可以使得正確的三維圖更清晰:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator
# generate example data
import numpy as np
x,y = np.meshgrid(np.linspace(-1,1,15),np.linspace(-1,1,15))
z = np.cos(x*np.pi)*np.sin(y*np.pi)
# actual plotting example
fig = plt.figure()
ax1 = fig.add_subplot(121, projection='3d')
ax1.plot_surface(x,y,z,rstride=1,cstride=1,cmap='viridis')
ax2 = fig.add_subplot(122)
cf = ax2.contourf(x,y,z,51,vmin=-1,vmax=1,cmap='viridis')
cbar = fig.colorbar(cf)
cbar.locator = LinearLocator(numticks=11)
cbar.update_ticks()
for ax in {ax1, ax2}:
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_aspect('equal')
ax1.set_zlim([-1,1])
ax1.set_zlabel(r'$\cos(\pi x) \sin(\p i y)$')
plt.show()