Matplotlib是一個Python工具箱,用於科學計算的數據可視化。借助它,Python可以繪制如Matlab和Octave多種多樣的數據圖形。下面這篇文章主要介紹了python使用matplotlib如何繪制折線圖的方法教程,需要的朋友可以參考借鑒。
matplotlib簡介
matplotlib 是python最著名的繪圖庫,它提供了一整套和matlab相似的命令API,十分適合交互式地行制圖。而且也可以方便地將它作為繪圖控件,嵌入GUI應用程序中。
它的文檔相當完備,並且Gallery頁面中有上百幅縮略圖,打開之后都有源程序。因此如果你需要繪制某種類型的圖,只需要在這個頁面中瀏覽/復制/粘貼一下,基本上都能搞定。
在Linux下比較著名的數據圖工具還有gnuplot,這個是免費的,Python有一個包可以調用gnuplot,但是語法比較不習慣,而且畫圖質量不高。
而 Matplotlib則比較強:Matlab的語法、python語言、latex的畫圖質量(還可以使用內嵌的latex引擎繪制的數學公式)。
繪圖庫Matplotlib的安裝方法:點擊這里
matplotlib繪制折線圖
1. line chart
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y1, y2 = np.sin(x), np.cos(x) plt.plot(x, y1) plt.plot(x, y2) plt.title('line chart') plt.xlabel('x') plt.ylabel('y') plt.show()
2. 圖例
在plot的時候指定label,然后調用legend方法可以繪制圖例。例如:
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y1, y2 = np.sin(x), np.cos(x) plt.plot(x, y1, label='y = sin(x)') plt.plot(x, y2, label='y = cos(x)') plt.legend() plt.show()
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)可以改變線的粗細,其值為浮點數。
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y1, y2 = np.sin(x), np.cos(x) plt.plot(x, y1, c='r', ls='--', lw=3) plt.plot(x, y2, c='#526922', ls='-.') plt.show()
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
例如:
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 10) y1, y2 = np.sin(x), np.cos(x) plt.plot(x, y1, marker='o', mec='r', mfc='w') plt.plot(x, y2, marker='*', ms=10) plt.show()
另外,marker關鍵字參數可以和color以及linestyle這兩個關鍵字參數合並為一個字符串。例如:
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 10) y1, y2 = np.sin(x), np.cos(x) plt.plot(x, y1, 'ro-') plt.plot(x, y2, 'g*:', ms=10) plt.show()
The kwargs are Line2D properties:
Property | Description |
---|---|
agg_filter | unknown |
alpha | float (0.0 transparent through 1.0 opaque) |
animated | [True | False] |
antialiased or aa | [True | False] |
axes | an Axes instance |
clip_box | a matplotlib.transforms.Bbox instance |
clip_on | [True | False] |
clip_path | [ (Path, Transform) | Patch | None ] |
color or c | any matplotlib color |
contains | a callable function |
dash_capstyle | [‘butt’ | ‘round’ | ‘projecting’] |
dash_joinstyle | [‘miter’ | ‘round’ | ‘bevel’] |
dashes | sequence of on/off ink in points |
drawstyle | [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] |
figure | a matplotlib.figure.Figure instance |
fillstyle | [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’] |
gid | an id string |
label | string or anything printable with ‘%s’ conversion. |
linestyle or ls | ['-' | '--' | '-.' | ':' | 'None' | ' ' | ''] |
linewidth or lw | float value in points |
lod | [True | False] |
marker | A valid marker style |
markeredgecolor or mec | any matplotlib color |
markeredgewidth or mew | float value in points |
markerfacecolor or mfc | any matplotlib color |
markerfacecoloralt or mfcalt | any matplotlib color |
markersize or ms | float |
markevery | [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float] |
path_effects | unknown |
picker | float distance in points or callable pick function fn(artist, event) |
pickradius | float distance in points |
rasterized | [True | False | None] |
sketch_params | unknown |
snap | unknown |
solid_capstyle | [‘butt’ | ‘round’ | ‘projecting’] |
solid_joinstyle | [‘miter’ | ‘round’ | ‘bevel’] |
transform | a matplotlib.transforms.Transform instance |
url | a url string |
visible | [True | False] |
xdata | 1D array |
ydata | 1D array |
zorder | any number |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對我的支持。