爲了將matplotlib
繪製的圖表嵌入到Notebook
中,需要執行下面的命令:
%matplotlib inline
- 載入matplotlib的繪圖模塊pyplot,並且重命名爲plt。
- 載入numpy模塊,並且重命名爲np。
import matplotlib.pyplot as plt
import numpy as np
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
np.linspace
在指定的間隔內返回均勻間隔的數字。 返回num均勻分佈的樣本,在[start, stop]。
x = np.linspace(0, 10, 100)
y = np.sin(x)
z = np.cos(x**2)
調用figure()
對象創建一個Figure(圖像)
對象,並且將它成爲當前Figure對象。figure參數指定了Figure對象的寬度和高度,單位爲英尺。此外還可以使用dpi
參數指定Figure對象的分辨率,即每英尺所表示的像素數,這裏使用默認值80
.
plt.figure(figsize=(8, 4))
<Figure size 576x288 with 0 Axes>
<Figure size 576x288 with 0 Axes>
這裏使用plot()
在當前的Figure對象中繪圖。實際上plot()
是在Axes(子圖)
對象上繪圖,如果不存在,則創建一個幾乎充滿整個圖表的Axes對象,使其成爲當前的Axes對象。
plot
前兩個參數分別表示X,Y軸數據的對象,這裏使用的是numpy
數組。使用關鍵字參數可以指定所繪製曲線的各種屬性。
- label: 給曲線指定一個標籤,也可以使用LaTeX表示,如果標籤字符串前後有字符
$
- color: 指定曲線的顏色,顏色可以用英文單詞或以
#
字符開頭的6位十六進制數表示。 - linewidth: 指定曲線的寬度,可以不是整數,或者使用縮寫
lw
。 b--
指定曲線的顏色和線型,b
表示藍色,--
表示線型爲虛線。
但是使用LaTeX語法繪製數學公式會極大的降低圖表的描繪速度
plt.plot(x, y, label="$sin(x)$", color="red", linewidth=2)
plt.plot(x, z, "b--", label="$cos(x^2)$")
[<matplotlib.lines.Line2D at 0x7f71dee853c8>]
plt.plot? #在IPython中執行可以查看格式化字符串的詳細說明。
xlabel, ylabel
:分別設置X, Y軸的標題文字。
plt.xlabel("Times(s)")
Text(0.5,0,'Times(s)')
plt.ylabel("vlot")
Text(0,0.5,'vlot')
title
設置子圖的標題
plt.title("Pyplot First Example")
Text(0.5,1,'Pyplot First Example')
xlim, ylim
分別設置X, Y 軸的顯示範圍。
plt.ylim(-1.2,1.2)
(-1.2, 1.2)
legend
顯示圖中曲線的標籤和樣式的矩陣區域。
plt.legend()
No handles with labels found to put in legend.
<matplotlib.legend.Legend at 0x7f71df083fd0>
最後調用plt.show()
顯示繪圖窗口。
plt.show()
將上面合併執行,結果如下。
plt.plot(x, y, label="$sin(x)$", color="red", linewidth=2)
plt.plot(x, z, "b--", label="$cos(x^2)$")
plt.xlabel("Times(s)")
plt.ylabel("vlot")
plt.ylim(-1.2,1.2)
plt.legend()
plt.show()
plt.savefig()
將當前的Figure對象保存爲圖像文件,圖像格式由圖像文件的擴展名決定,可以通過dpi
參數來指定圖像的分辨率。
plt.savefig("test.png", dpi=120)
<Figure size 432x288 with 0 Axes>