改變線的顏色和線寬
參考文章:
線有很多屬性你可以設置:線寬,線型,抗鋸齒等等;具體請參考matplotlib.lines.Line2D
有以下幾種方式可以設置線的屬性
-
使用關鍵字參數
plt.plot(x, y, linewidth=2.0) -
使用 Line2D 對象的設置方法。 plot 返回一個 Line2D 對象的列表; line1, line2 = plot(x1, y1, x2, y2)。 下面的代碼中我們假定圖中僅有一條線以使返回的列表的長度為1。我們使用
line,進行元組展開,來獲得列表的首個元素。line, = plt.plot(x, y, '-') line.set_antialiased(False) # 關閉抗鋸齒 -
使用 setp() 命令。下面給出的例子使用Matlab樣式命令來設置對列表中的線對象設置多種屬性。
setp可以作用於對象列表或僅僅一個對象。你可以使用Python關鍵字的形式或Matlab樣式。lines = plt.plot(x1, y1, x2, y2) # use keyword args plt.setp(lines, color='r', linewidth=2.0) # or MATLAB style string value pairs plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
設置坐標軸范圍
參考文檔:
下面以 xlim() 為例進行說明:
獲取或設置當前圖像 x 軸的范圍:
xmin, xmax = xlim() # return the current xlim
xlim( (xmin, xmax) ) # set the xlim to xmin, xmax
xlim( xmin, xmax ) # set the xlim to xmin, xmax
或者可以下面這樣:
xlim(xmax=3) # adjust the max leaving min unchanged
xlim(xmin=1) # adjust the min leaving max unchanged
設置 x-axis limits 會使得 autoscaling 自動關閉,即兩者不能同時設置。
以上說明綜合舉例如下:
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 5), dpi=80)
plt.subplot(111)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
S = np.sin(X)
C = np.cos(X)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.show()
生成的圖像:

