Matplotlib
2022/01/11 by JohnAxer
基本觀念
- 畫圖當然要先有畫布,這個畫布就是「圖」,一張圖可以再分為幾個子圖,每個子圖都可以有一到多個軸空間,每個軸空間可以有1到多個軸。
- 一個圖至少有一個子圖,每個子圖至少有一個軸空間,軸空間必包含軸。
- 圖 figure
- 子圖 subplot
- 軸空間 axes
- 軸 axis
兩種寫法
-
預計的執行結果
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
-
物件導向的寫法 OO-style
- 注意到第16行,如果一個圖要包含多個子圖,可以這樣宣告。
fig, ax = plot.subplots(2, 1)
- 這樣就有兩個子圖,呈兩列(row)一欄(column)的排列。此時 ax 是一個 ndarray,裡面有兩個子圖 (AxesSubplot)。這個可以用
print(ax) 和 print(type(ax))
- 函數的寫法 pyplot-style
- 在 pyplot-style 的寫法下,我們其實可以直接用 plot 直接繪圖,因為 matplotlib 會自動幫我們建立一個圖(包含1個子圖)和軸空間。
- 第16行,如果我們想要有2個子圖,呈兩列(row)一欄(column)的排列,這時可以用
plot.subplot(2, 1, 1)
其中第3個參數,表示目前在第幾個子圖。這個函數一樣會傳回一個子圖物件。
有哪些圖形呢?
- 折線圖 line
- 長條圖 bar
- 橫向長條圖 barh
- 直方圖 hist
- 盒狀圖 box
- 圓餅圖 pie
- 散布圖 scatter
- 密度圖 density
- 六邊箱圖 hexbin
- 區域圖 area (折線圖+向下填滿)
- 核密度估計圖 kde
資料點和線的樣式
解決中文顯示問題
搭配 Pandas
-
使用 iris.csv
-
資料集中有五項數據
- Sepal length: 花萼長度 (cm)
- Sepal width: 花萼寬度 (cm)
- Petal length: 花瓣長度 (cm)
- Petal width: 花瓣寬度 (cm)
- Variety: 鳶尾花的種類
-
資料集的前10筆
-
示範程式
-
執行結果
- 這種方式,所有資料列屬於同一資料類,所以,圖示(legend)無法自動產生,得用另一種方式。
- legend 產生方式(未完待續)。
- 執行結果
