## 用Python畫出等高線,並且設定xy軸刻度標籤
阿新 • • 發佈:2018-12-08
import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(9, 6)) # 定義等高線高度函式 def f(x, y): return (pow(x,3)+pow(y,3)-15*x-20*y)+9 # 資料數目 n = 256 # 定義x, y x = np.linspace(-5, 5, n) y = np.linspace(-3, 2, n) # 生成網格資料 X, Y = np.meshgrid(x, y) # 填充等高線的顏色, 8是等高線分為幾部分 plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.prism) # 繪製等高線 C = plt.contour(X, Y, f(X, Y), 8, colors = 'black', linewidth = 0.5) #使得上面右邊都有刻度線,direction指明刻度線方向,可選out plt.tick_params(right=True, top=True,labelsize=10, direction='in', pad=3, length=4) x_ticks = np.linspace(5, -5, 8)#發現如果是np.arrange(5,-5,8)就不能畫上去 x_labels = ['1990', '1991', '1992', '1993', '1994', '1995','1996','1997'] y_ticks = np.linspace(-3, 2, 5) y_labels = ['', '5', '10', '15', '20', '25'] #畫刻度線和xy軸的標籤 plt.xticks(x_ticks, x_labels, fontsize=9) plt.yticks(y_ticks, y_labels, fontsize=9) plt.show()
程式碼與圖片元素對應關係在註釋裡寫的很清楚哦