Matplotlib繪圖教程的使用
Matplotlib是一個Python工具箱,用於科學計算的資料視覺化。藉助它,Python可以繪製如Matlab和Octave多種多樣的資料圖形。下面這篇文章主要介紹了python使用matplotlib如何繪製折線圖的方法教程,需要的朋友可以參考借鑑。
1. line chart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
= np.linspace( 0 , 2 * np.pi, 100 )
|
2. 圖例
在plot的時候指定label,然後呼叫legend方法可以繪製圖例。例如:
1 2 3 4 5 6 7 8 9 10 |
|
legend方法可接受一個loc關鍵字引數來設定圖例的位置,可取值為數字或字串:
0: ‘best'
1: ‘upper right'
2: ‘upper left'
3: ‘lower left'
4: ‘lower right'
5: ‘right'
6: ‘center left'
7: ‘center right'
8: ‘lower center'
9: ‘upper center'
10: ‘center'
3. 線的樣式
(1)顏色
plot方法的關鍵字引數color(或c)用來設定線的顏色。可取值為:
1、顏色名稱或簡寫
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white
2、#rrggbb
3、(r, g, b) 或 (r, g, b, a),其中 r g b a 取均為[0, 1]之間
4、[0, 1]之間的浮點數的字串形式,表示灰度值。0表示黑色,1表示白色
(2)樣式
plot方法的關鍵字引數linestyle(或ls)用來設定線的樣式。可取值為:
- -, solid
- --, dashed
- -., dashdot
- :, dotted
- '', ' ', None
(3)粗細
設定plot方法的關鍵字引數linewidth(或lw)可以改變線的粗細,其值為浮點數。
1 2 3 4 5 6 7 8 9 |
|
4. marker
以下關鍵字引數可以用來設定marker的樣式:
- marker
- markeredgecolor 或 mec
- markeredgewidth 或 mew
- markerfacecolor 或 mfc
- markerfacecoloralt 或 mfcalt
- markersize 或 ms
其中marker可取值為:
- '.': point marker
- ',': pixel marker
- 'o': circle marker
- 'v': triangle_down marker
- '^': triangle_up marker
- '<': triangle_left marker
- '>': triangle_right marker
- '1': tri_down marker
- '2': tri_up marker
- '3': tri_left marker
- '4': tri_right marker
- 's': square marker
- 'p': pentagon marker
- '*': star marker
- 'h': hexagon1 marker
- 'H': hexagon2 marker
- '+': plus marker
- 'x': x marker
- 'D': diamond marker
- 'd': thin_diamond marker
- '|': vline marker
- '_': hline marker
例如:
1 2 3 4 5 6 7 8 9 |
|
另外,marker關鍵字引數可以和color以及linestyle這兩個關鍵字引數合併為一個字串。例如:
1 2 3 4 5 6 7 8 9 |
|
The kwargs are Line2D properties:引數設定
Property | Description |
---|---|
alpha | float (0.0 transparent through 1.0 opaque) |
[True | False] | |
axes | an Axes instance |
[True | False] | |
color or c | any matplotlib color |
a callable function | |
[‘butt’ | ‘round’ | ‘projecting’] | |
[‘miter’ | ‘round’ | ‘bevel’] | |
sequence of on/off ink in points | |
[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] | |
[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’] | |
gid | an id string |
label | string or anything printable with ‘%s’ conversion. |
['-' | '--' | '-.' | ':' | 'None' | ' ' | ''] | |
float value in points | |
lod | [True | False] |
any matplotlib color | |
float value in points | |
any matplotlib color | |
[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float] | |
float distance in points or callable pick function fn(artist, event) | |
float distance in points | |
[True | False | None] | |
snap | unknown |
[‘butt’ | ‘round’ | ‘projecting’] | |
[‘miter’ | ‘round’ | ‘bevel’] | |
url | a url string |
[True | False] | |
xdata | 1D array |
ydata | 1D array |
any number |