Matplotlib簡介
Matplotlib是一個Python工具箱,用于科學(xué)計算的數(shù)據(jù)可視化。借助它,Python可以繪制如Matlab和Octave多種多樣的數(shù)據(jù)圖形。最初是模仿了Matlab圖形命令, 但是與Matlab是相互獨立的.
通過Matplotlib中簡單的接口可以快速的繪制2D圖表
初試Matplotlib
Matplotlib中的pyplot子庫提供了和matlab類似的繪圖API.
代碼如下:
import matplotlib.pyplot as plt #導(dǎo)入pyplot子庫
plt.figure(figsize=(8, 4)) #創(chuàng)建一個繪圖對象, 并設(shè)置對象的寬度和高度, 如果不創(chuàng)建直接調(diào)用plot, Matplotlib會直接創(chuàng)建一個繪圖對象
plt.plot([1, 2, 3, 4]) #此處設(shè)置y的坐標為[1, 2, 3, 4], 則x的坐標默認為[0, 1, 2, 3]在繪圖對象中進行繪圖, 可以設(shè)置label, color和linewidth關(guān)鍵字參數(shù)
plt.ylabel('some numbers') #給y軸添加標簽, 給x軸加標簽用xlable
plt.title("hello"); #給2D圖加標題
plt.show() #顯示2D圖
基礎(chǔ)繪圖
繪制折線圖
與所選點的坐標有關(guān)
代碼如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
plt.plot(x, y, '-*r') # 虛線, 星點, 紅色
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
更改線的樣式查看plot函數(shù)參數(shù)設(shè)置
多線圖
只需要在plot函數(shù)中傳入多對x-y坐標對就能畫出多條線
代碼如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.plot(x, y, '--*r', x, z, '-.+g')
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("hello world")
plt.show()
柱狀圖
代碼如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.bar(x, y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
子圖
subplot()函數(shù)指明numrows行數(shù), numcols列數(shù), fignum圖個數(shù). 圖的個數(shù)不能超過行數(shù)和列數(shù)之積
代碼如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.figure(1)
plt.subplot(211)
plt.plot(x, y, '-+b')
plt.subplot(212)
plt.plot(x, z, '-.*r')
plt.show()
文本添加
當需要在圖片上調(diào)價文本時需要使用text()函數(shù), 還有xlabel(), ylabel(), title()函數(shù)
text()函數(shù)返回matplotlib.text.Text, 函數(shù)詳細解釋
代碼如下:
新聞熱點
疑難解答
圖片精選