Matplotlib是一個Python工具箱,用於科學計算的數據可視化。借助它,Python可以繪制如Matlab和Octave多種多樣的數據圖形。
安裝
Matplotlib並不是Python的默認組件,需要額外安裝。
官方下載地址 http://matplotlib.org/downloads.html
必須下載與自己的Python版本,操作系統類型對應的安裝包。如Windows 64位+Python3.3,應該下載matplotlib-1.3.1.win-amd64-py3.3.exe
第一個程序
讓我們運行第一個Matplotlib程序:
import matplotlib.pyplot as plt plt.plot([1, 2, 3]) plt.ylabel('some numbers') plt.show()
如果Matplotlib已經正確安裝,您將會看到如下結果:
這個彈出窗口就是Matplotlib的繪圖輸出窗口,底部從左到右有七個按鈕:
-
- 重置視圖,顯示最初的視圖
- 上一個視圖
- 下一個視圖
- 移動工具,用於拖動繪圖的顯示區域
- 縮放工具,可以拖拽一個矩形縮放到窗口大小
- 配置工具,調整繪圖選項
- 保存圖片
接下來我們一起分析這個短小的程序代碼。
第1行:
import matplotlib.pyplot as plt
調用matplotlib的pyplot繪圖工具,之后我們就可以使用plt代替matplotlib.pyplot使用了。
第2行:
plt.plot([1, 2, 3])
繪制一個折線圖。plot()方法用於繪制折線圖,pyplot還有繪制柱狀圖、餅圖的方法。[1,2,3]是Y坐標,而缺省的X坐標為[0,1,2]。兩個一維數組X和Y構成了折線關鍵點的坐標(0,1),(1,2),(2,3)。您可以嘗試修改參數如:
plt.plot([0, 1, 2, 3], [0.1, 0.2, 0.15, 0.3]) # 第一個數組是X坐標,第二個數組是Y坐標
第3行:
plt.ylabel('some numbers')
為Y坐標軸添加標簽,通常用以標注此變量的名稱和單位。當然X軸也是可以添加標簽的:
plt.xlabel('Time (s)') plt.ylabel('Speed (m/s)')
第4行:
plt.show()
顯示繪圖窗口。在繪圖完成之后,我們要調用這個方法才能打開繪圖輸出窗口。
另一種圖形輸出方式是保存圖片,缺點是不能使用縮放、移動等交互瀏覽功能:
plt.save('output.png')
基本繪圖
折線圖和散點圖-plot()
plot()函數可以繪制折線圖和折線圖,取決於您使用的參數。
數據和坐標
一個最簡單的例子:
import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [0.1, 0.2, 0.2, 0.3, 0.2, 0.1] plt.plot(x, y) plt.show()
繪制折線圖/散點圖需要一系列關鍵點。x是關鍵點的x軸坐標,y是關鍵點的y軸坐標。
x | y |
---|---|
0 | 0.1 |
1 | 0.2 |
2 | 0.2 |
3 | 0.3 |
4 | 0.2 |
5 | 0.1 |
未附加額外參數時,將繪制最基本的折線圖:
x軸坐標是可以缺省的:
plot(y)
y是一個一維數組,是折線圖關鍵點的y軸坐標。而x軸坐標沒有給出,會默認以[0,1,2,...]的常數列作為x軸坐標。
樣式
散點圖和折線圖只是線條樣式的差異,我們可以通過簡單的參數設置線條的樣式和顏色。樣式和顏色參數都是一個或多個字符構成的字符串。
-
- 既可以單獨設定顏色或樣式,如'g'代表綠色,'-'代表實線
- 也可以同時設定樣式和顏色,比如'--g'代表綠色虛線,其中'--'代表虛線,'g'代表綠色
- 樣式字符串中的參數字符是無順序的,'g--'和'--g'的意義是相同的
- 也可以同時設定折線和散點,如'-or'代表紅色實線+圓圈
例子:
import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [0.1, 0.2, 0.2, 0.3, 0.2, 0.1] plt.plot(x, y, '-or') plt.show()
折線樣式:
參數 | 樣式 |
---|---|
'-' | 實線 |
'--' | 虛線 |
'-.' | 線-點 |
':' | 點虛線 |
散點樣式:
參數 | 樣式 |
---|---|
'.' | 實心點 |
'o' | 圓圈 |
',' | 一個像素點 |
'x' | 叉號 |
'+' | 十字 |
'*' | 星號 |
'^' 'v' '<' '>' | 三角形(上下左右) |
'1' '2' '3' '4' | 三叉號(上下左右) |
顏色:
參數 | 顏色 |
---|---|
'b' | 藍 |
'g' | 綠 |
'r' | 紅 |
'c' | 青 |
'm' | 品紅 |
'y' | 黃 |
'k' | 黑 |
'w' | 白 |
更多樣式參見 http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
您也可以不必使用樣式字符串,而直接使用參數名,這種方式更加靈活:
plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12)
多條線
我們可以在一個坐標中繪制多條折線或散點,plot(第一條線的參數,第二條線的參數...):
import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [0.1, 0.2, 0.2, 0.3, 0.2, 0.1] y2 = [0.2, 0.2, 0.3, 0.2, 0.3, 0] plt.plot(x, y, 'b', x, y2, 'g') plt.show()
柱狀圖-bar()
bar()函數可以繪制各種樣式的柱狀圖,barh()則可繪制水平方向的柱狀圖。兩個方法除了繪圖方向外,其他屬性和用法的是相同的。
數據和坐標
bar()至少需要兩個數組left和height:left是每個柱向左到坐標原點的距離;height是每個柱的高度。
import matplotlib.pyplot as plt left = [0, 1, 2, 3, 4, 5] height = [0.1, 0.2, 0.2, 0.3, 0.2, 0.1] plt.bar(left, height) plt.show()
樣式
bar()函數的參數可以控制柱狀圖的多種樣式,最常用的有:
-
- width,第3個參數,柱的寬度。可以是一個常數或數組。數組將對每條柱設定不同的值。
- bottom,第4個參數,柱底部的y軸坐標。可以是一個常數或數組。數組將對每條柱設定不同的值。
- color,關鍵字參數,柱的填充顏色。可以是一個常數或數組。數組將對每條柱設定不同的值。
- edgecolor,關鍵字參數,柱的邊框顏色。
- linewidth,關鍵字參數,邊框寬度。
- xerr,yerr,關鍵字參數,x和y軸誤差線。
- ecolor,關鍵字參數,誤差線顏色。
提示 | 以上參數都可以是一個常數或數組。常數為所有柱設定相同的值,數組將對每條柱設定不同的值。 |
-
- align,關鍵字參數,設定柱的對齊方式。'edge'將x坐標設為左邊界,'center'將x坐標設為中軸線。
下面的柱狀圖要表達一件商品12個月的銷量:
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] sales = [112, 105, 111, 109, 103, 110, 113, 112, 108, 106, 111, 114] plt.bar(month, sales, 0.5, color='y', edgecolor='g', linewidth=3, align='center') plt.show()
我們設置柱寬度0.5,填充顏色'y'(黃色),邊框顏色'g'(綠色),線框寬度3,對齊方式為'center'
為了讓銷量變化看起來更明顯,我們現在只繪出100以上的部分:
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] sales = [12, 5, 11, 9, 3, 10, 13, 12, 8, 6, 11, 14] plt.bar(month, sales, 0.5, 100, color='y', edgecolor='g', linewidth=3, align='center') plt.show()
我們添加了新的參數,設置柱狀圖的底部為100,而sales數據則減去100。
現在我們想將四個季度用顏色區分出來:
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] sales = [12, 5, 11, 9, 3, 10, 13, 12, 8, 6, 11, 14] colors = ['g', 'g', 'g', 'm', 'm', 'm', 'y', 'y', 'y', 'c', 'c', 'c'] plt.bar(month, sales, 0.5, 100, color=colors, linewidth=0, align='center') plt.show()
我們用一個數組來存儲每個柱的顏色,其長度必須與month和sales相同。
多段柱圖和水平柱圖
繪制多段柱圖的原理是:先后繪制多張柱圖,依次重疊在上方,如果后面繪制的柱圖比前者的柱圖短,就可以顯示出前者長出的部分。
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] bar1 = plt.bar(month, profit, 0.5, color='y', linewidth=0, align='center') bar2 = plt.bar(month, cost, 0.5, color='g', linewidth=0, align='center') plt.legend( (bar1[0], bar2[0]), ('Profits', 'Costs') ) plt.show()
我們還是用了legend()方法標識兩段柱圖的圖例。legend()的更多用法見#繪圖樣式一節。
最后,讓我們來繪制一個水平柱圖,只需將bar()替換成barh():
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] bar1 = plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') bar2 = plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') plt.legend( (bar1[0], bar2[0]), ('Profits', 'Costs') ) plt.show()
圓餅圖-pie()
pie()是繪制餅圖的函數。
數據
pie()最基本的輸入數據是一個數組。它可以根據數組元素的比例繪制扇形,因此不必要事先計算好百分比。
import matplotlib.pyplot as plt rate = [1, 7, 3, 9] plt.pie(rate) plt.show()
樣式
有幾個最常用的參數可以控制繪圖樣式:
-
- colors - 數組,扇形顏色
- explode - 數組,扇形偏離圓心的距離
- labels - 數組,扇形的標簽
首先,讓我們為餅圖設定顏色,並讓第三個扇形抽離出來:
import matplotlib.pyplot as plt rate = [1, 7, 3, 9] explode = [0, 0, 0.1, 0] colors = ['c', 'm', 'y', 'g'] plt.pie(rate, explode=explode, colors=colors) plt.show()
然后,要為每個扇形添加標簽:
import matplotlib.pyplot as plt rate = [1, 7, 3, 9] explode = [0, 0, 0.1, 0] colors = ['c', 'm', 'y', 'g'] labels = ['Apple', 'Pear', 'Peach', 'Orange'] plt.pie(rate, explode=explode, colors=colors, labels=labels) plt.show()
百分比
如何顯示百分比數值呢?我們需要使用autopct參數:
-
- None,不顯示百分比
- 格式字符串,如'%d percent',顯示“40 percent”形式的百分比
- 方法,調用方法輸出百分比
import matplotlib.pyplot as plt rate = [1, 7, 3, 9] explode = [0, 0, 0.1, 0] colors = ['c', 'm', 'y', 'g'] labels = ['Apple', 'Pear', 'Peach', 'Orange'] plt.pie(rate, explode=explode, colors=colors, labels=labels, autopct='%d%%') plt.show()
autopct='%d%%'表示我們將百分比以整數(%d)形式輸出,后綴是百分號'%'。在格式化字符串中,百分號要用'%%'轉義字符表示。
繪圖樣式
這一節介紹如何為圖表添加標題,刻度,標簽,圖例,注釋等元素,讓圖表更加清晰易懂。
標題-title()
title()方法用於繪制圖表標題,一般位於頂部。最簡單的方法是使用title('title'),繪制默認格式的標題文本。
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') plt.title('Sales Statistics') plt.show()
若只想設置水平對齊,可以直接使用loc參數:
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') plt.title('Sales Statistics', loc='right') plt.show()
您也可以額外使用fontdict參數定義格式,fontdict是一個字典數據(dict),有以下字段
-
- 'fontsize': 字體大小
- 'verticalalignment': 垂直對齊
- 'horizontalalignment': 水平對齊
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') font = {'fontsize': 22, 'verticalalignment': 'bottom', 'horizontalalignment': 'center'} plt.title('Sales Statistics', fontdict=font) plt.show()
刻度-xticks()&yticks()
xticks()和yticks()會修改默認的x軸y軸刻度。
繼續上一個例子,現在我們將要把y軸的刻度從1,2,3...換成月份Jan,Feb,Mar...
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') plt.title('Sales Statistics') ticks = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] plt.yticks(month, ticks) plt.show()
yticks()有兩個參數,第一個數組是每個刻度的位置,第二個數組是各個刻度。兩個數組等長,設定某刻度的值應該定位於何處。
標簽-xlabel()&ylabel()
接下來,添加x軸和y軸的標簽:
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') plt.title('Sales Statistics') ticks = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] plt.yticks(month, ticks) plt.xlabel('Money (10000RMB)') plt.ylabel('Month') plt.show()
圖例-legend()
因為有多段柱圖,黃色和綠色,我們需要圖例區分它們的含義:
import matplotlib.pyplot as plt month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] cost = [8, 7, 9, 9, 3, 10, 10, 12, 8, 6, 11, 10] profit = [12, 11, 11, 13, 5, 11, 13, 15, 10, 9, 12, 13] bar1 = plt.barh(month, profit, 0.5, color='y', linewidth=0, align='center') bar2 = plt.barh(month, cost, 0.5, color='g', linewidth=0, align='center') plt.title('Sales Statistics') ticks = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] plt.yticks(month, ticks) plt.xlabel('Money (10000RMB)') plt.ylabel('Month') plt.legend( (bar1[0], bar2[0]), ('Profits', 'Costs') ) plt.show()
legend()有兩個數組參數:第一個是樣式對象,比如這里選了bar1的第1個柱,bar2的第1個柱(如果是折線圖則是某一點的樣式);第二個是描述字符,對應描述每一個樣式。
子圖-subplot()
使用subplot()替代plot,可以在同一畫布里繪制多個圖表,它們的數量,大小都是可調的。