matplotlib圖像繪製 / matplotlib image descriptionhtml
目錄數組
1 關於matplotlib / About matplotlibdom
Matplotlib 是一個 Python 的 2D繪圖庫,它以各類硬拷貝格式和跨平臺的交互式環境生成出版質量級別的圖形。相應內容可參考 matplotlib 官網。ide
Matplotlib基礎知識函數
1. Matplotlib中的基本圖表包括的元素fetch
2. hold屬性spa
3. 網格線與grid方法3d
4. axis方法code
5. xlim方法和ylim方法orm
6. legend
7. Figure和AxesSubplot
2 matplotlib庫 / matplotlib Library
環境安裝:
pip install matplotlib
2.1 常量 / Constants
Pass
2.2 函數 / Function
Pass
2.3 類 / Class
2.3.1 Figure類
類實例化:fig = plt.figure(fig_name, figsize=)
類的功能:用於生成Figure
傳入參數: fig_name, figsize
fig_name: str類型,Figure的名稱
figsize: tuple類型,肯定fig的長寬大小
返回參數: fig
fig: Figure類型,<class 'matplotlib.figure.Figure'>,生成的Figure
2.3.1.1 add_subplot()方法
函數調用:ax = fig.add_subplot(r, c, p)
函數功能:生成繪圖區域子圖
傳入參數: r, c, p
r: int類型,fig區域等分行數
c: int類型,fig區域等分列數
p: int類型,ax所在fig位置處
返回參數: ax
ax: AxesSubplot類型,<class 'matplotlib.axes._subplots.AxesSubplot'>,生成的AxesSubplot
2.3.2 AxesSubplot類
類實例化:ax = plt.subplot(r, c, p) / fig.add_subplot(r, c, p)
類的功能:生成繪圖區域
傳入參數: r, c, p
r: int類型,fig區域等分行數
c: int類型,fig區域等分列數
p: int類型,ax所在fig位置處
返回參數: ax
ax: AxesSubplot類型,<class 'matplotlib.axes._subplots.AxesSubplot'>,生成的AxesSubplot
Note: 實際上plt.subplot()函數最終調用的也是fig.add_subplot()函數
2.3.2.1 plot()方法
函數調用: ax.plot(x_list, y_list, c=, label=)
函數功能:繪製曲線圖
傳入參數: x_list, y_list, c, label
x_list: list類型,全部須要繪製的點的橫座標列表
y_list: list類型,全部須要繪製的點的縱座標列表
c: str/tuple類型,設置線條的顏色,可使用名稱‘red’/縮寫‘r’/RGB(1, 0, 0),其中RGB元組中的全部值爲x/255,在0-1之間
label: str類型,線條的標籤名(在legend上顯示)
返回參數: 無
2.3.2.2 bar / barh()方法
函數調用: ax.bar / barh(bar_position, bar_height, bar_width)
函數功能:繪製柱狀圖(縱向或者橫向)
傳入參數: bar_position, bar_height, bar_width
bar_position: list類型,全部須要繪製的柱形的橫座標位置列表
bar_height: list類型,全部須要繪製的柱形的高度列表
bar_width: int類型,柱形的寬度
返回參數: 無
2.3.2.3 boxplot()方法
函數調用: ax.boxplot(data)
函數功能:繪製箱圖
傳入參數: data
data: array/a sequence of vector類型,進行繪圖的二維數組,按列分組
返回參數: 無
2.3.2.4 scatter()函數
函數調用: ax.scatter(x, y)
函數功能:繪製散點圖
傳入參數: x, y
x: list/Series類型,繪製散點圖的x座標集合
y: list/Series類型,繪製散點圖的y座標集合
返回參數: 無
2.3.2.5 hist()方法
函數調用: ax.hist(x, bins=None, range=None)
函數功能:繪製histogram直方圖
傳入參數: x, bins, range
x: array/a sequence of array類型,數據點集合,不要求同長度
bins: int類型,繪製的直方圖分割數量
range: tuple類型,須要繪製直方圖的數據範圍
返回參數: 無
2.3.2.6 set_xticks / set_yticks()方法
函數調用: ax.set_xticks / set_yticks(posi_list)
函數功能:設置ticks的位置
傳入參數: posi_list
posi_list: list類型,各個ticks離原點座標的距離
返回參數: 無
2.3.2.7 set_xticklabels / set_yticklabels()方法
函數調用: ax.set_xticklabels / set_yticklabels(name_list, rotation=0)
函數功能:設置ticks的名稱
傳入參數: name_list, rotation
name_list: list類型,各個ticks的名稱
rotation: int類型,label順時針旋轉的角度
返回參數: 無
2.3.2.8 set_xlabel / set_ylabel()方法
函數調用: ax.set_xlabel / set_ylabel(name)
函數功能:設置label的名稱
傳入參數: name
name: str類型,label的名稱
返回參數: 無
2.3.2.9 set_title()方法
函數調用: ax.set_title(name)
函數功能:設置title的名稱
傳入參數: name
name: str類型,title的名稱
返回參數: 無
2.3.2.10 set_xlim / set_ylim()方法
函數調用: ax.set_xlim / set_ylim(left, right)
函數功能:設置x/y軸的數值限制
傳入參數: left, right
left: int類型,數據的左端極值
right: int類型,數據的右端極值
返回參數: 無
2.3.2.11 tick_params()方法
函數調用: ax.tick_params(axis=‘both’, **kwarge)
函數功能:改變ticks或ticks的顯示狀態
傳入參數: axis, **kwarge
axis: str類型,‘x’/‘y’/‘both’肯定目標軸
**kwarge: 傳入包括color/bottom/top/left/right/length/width等參數進行設置
返回參數: 無
2.3.2.12 spines屬性
屬性調用: sp = ax.spines
屬性功能:獲取全部座標軸的一個類
屬性參數: sp
sp: obj類型,包含全部座標軸(left, right, bottom, top)信息的類
Note: 對於獲取到的sp,能夠經過for key, spine in sp.items()得到各個spine,並利用spine的set_visible(False)函數隱藏全部的spine
2.4 模塊 / Module
2.4.1 pyplot模塊
from matlibplot import pyplot as plt
2.4.1.1 常量
Pass
2.4.1.2 函數
2.4.1.2.1 figure()函數
函數調用:fig = plt.figure(fig_name, figsize=)
函數功能:用於生成Figure
傳入參數: fig_name, figsize
fig_name: str類型,Figure的名稱
figsize: tuple類型,肯定fig的長寬大小
返回參數: fig
fig: Figure類型,<class 'matplotlib.figure.Figure'>,生成的Figure
2.4.1.2.2 subplot()函數
類實例化:ax = plt.subplot(r, c, p)
類的功能:生成繪圖區域AxesSubplot
傳入參數: r, c, p
r: int類型,fig區域等分行數
c: int類型,fig區域等分列數
p: int類型,ax所在fig位置處
返回參數: ax
ax: AxesSubplot類型,<class 'matplotlib.axes._subplots.AxesSubplot'>,生成的AxesSubplot
Note: 實際上plt.subplot()函數最終調用的也是fig.add_subplot()函數
2.4.1.2.3 subplots()函數
類實例化:fig, ax = plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False)
類的功能:生成圖像Figure以及相應數量的繪圖區域子圖AxesSubplot
傳入參數: nrows, ncols, sharex, sharey
nrows: int類型,fig區域等分行數,即nrows個子圖在一行
ncols: int類型,fig區域等分列數,即ncols列子圖
sharex: bool類型,全部子圖是否共享x軸
sharey: bool類型,全部子圖是否共享y軸
返回參數: fig, ax
fig: Figure類型,生成的當前Figure
ax: AxesSubplot / list類型,當ax數量大於1時,ax爲全部子圖組成的ndarray
2.4.1.2.4 plot()函數
函數調用: plt.plot(x_list, y_list, c=, label=)
函數功能:對須要繪製的圖像點進行繪製處理(會對ax進行設置)
傳入參數: x_list, y_list, c, label
x_list: list類型,全部須要繪製的點的橫座標列表
y_list: list類型,全部須要繪製的點的縱座標列表
c: str/tuple類型,設置線條的顏色,可使用名稱‘red’/縮寫‘r’/RGB(1, 0, 0),其中RGB元組中的全部值爲x/255,在0-1之間
label: str類型,線條的標籤名(在legend上顯示)
返回參數: 無
2.4.1.2.5 xticks / yticks()函數
函數調用: plt.xticks / yticks(loc, name, rotation=0)
函數功能:對最近一個ax設置ticks(軸標記)
傳入參數: loc, name, rotation
loc: list類型,包含了每一個ticks到零點的距離
name: list類型,每一個ticks的名稱
rotation: ticks的旋轉角度
返回參數: 無
2.4.1.2.6 xlabel / ylabel()函數
函數調用: plt.xlabel / ylabel(name)
函數功能:對最近一個ax設置label名稱
傳入參數: name
name: str類型,label的名稱
返回參數: 無
2.4.1.2.7 title()函數
函數調用: plt.title(name)
函數功能:對最近一個ax設置title名稱
傳入參數: name
name: str類型,title的名稱
返回參數: 無
2.4.1.2.8 legend()函數
函數調用: plt.legend(loc=‘upper right’)
函數功能:對最近一個ax設置legend圖例參數
傳入參數: loc
loc: str類型,legend所在位置
返回參數: 無
Note:
loc - int or string or pair of floats, default: 'upper right'
The location of the legend. Possible codes are:
=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
2.4.1.2.9 show()函數
函數調用: plt.show()
函數功能:對全部的Figure類進行圖像顯示
傳入參數: 無
返回參數: 無
3.1 plt函數的做用範圍
對於plt函數,其實質依舊是調用了最近的ax的內部函數實現對title/legend/label等的設置,所以直接使用plt函數時需注意代碼位置,或者經過特定ax進行直接調用則不須要注意位置問題。
3.2 顏色數組RGB
在matplotlib中的顏色數組RGB內各個值的範圍均爲0-1,求值的方式爲x/255,下面是各個顏色的參考RGB值,除以255後可在matplotlib中使用。
3.3 箱圖
箱圖boxPlot是一種統計經常使用的圖形,可以充分顯示數據分佈的情況。下圖中包括了中位數,1/4位數,3/4位數的位置,過大或太小的點將以點形式額外表示出來。
繪製圖像的第一步在於生成相應的fig和ax,此處有3種方法用於生成fig與ax
首先導入模塊,
1 from matplotlib import pylab as plt
(1) 利用plt的subplots()函數直接同時生成fig和ax
1 fig, ax = plt.subplots() 2 print(fig, ax)
(2) 利用plt的figure()函數生成fig,再利用fig的add_subplot()函數生成ax
1 fig = plt.figure('New_Figure') 2 ax = fig.add_subplot(1, 1, 1) 3 print(fig, ax)
(3) 利用plt的figure()函數生成fig,再利用plt的subplot()函數生成ax
1 fig = plt.figure('Another_Figure') 2 ax = plt.subplot(1, 1, 1) 3 print(fig, ax)
最後使用show函數能夠獲得3張圖像,分別對應上面的名稱
1 plt.show()
子圖的生成方式有如下兩種,
1 # Two ways to create a figure with subplot 2 # First one: subplots 3 # plt.subplots(nrow, ncol) 4 # sharex and sharey decide whether all the subplot should to share the axis label 5 # If multi subplots, ax will be a array contains all subplots 6 fig, ax = plt.subplots(2, 2, sharex=False, sharey=False) 7 ax_1 = ax[0][0] 8 ax_2 = ax[0][1] 9 ax_3 = ax[1][0] 10 ax_4 = ax[1][1] 11 # Second one: use figure 12 fig = plt.figure('figure_name', figsize=(7, 7)) 13 ax_1 = fig.add_subplot(2, 2, 1) 14 ax_2 = fig.add_subplot(2, 2, 2) 15 16 plt.show()
顯示結果
完整代碼
1 import pandas as pd 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 curve = pd.read_csv('curve.csv') 6 print(curve) 7 print('------------') 8 # Change format to datetime format 9 curve['DATE'] = pd.to_datetime(curve['DATE']) 10 print(curve) 11 12 # matplotlib inline 13 # If plot nothing and show, it will plot and show a blank board 14 # plt.plot() 15 # plt.show() 16 # Similar to pyqtgraph, plot(x_list, y_list) 17 plt.plot(curve['DATE'], curve['VALUE']) 18 # If the tick is too long, use rotation to adjust 19 plt.xticks(rotation=-45) 20 plt.xlabel('Month') 21 plt.ylabel('Rate') 22 plt.title('Unemployment Rate') 23 #plt.show() 24 25 # Sub figure 26 # figsize decide the size of figure window 27 fig = plt.figure('figure_name', figsize=(7, 7)) 28 # add_subplot(row, column, location) 29 # add_subplot will divide fig into several part(according to row and column) and place the subplot in input location 30 ''' fig divided like that: 31 [1 ... x 32 . . 33 . . 34 . . 35 y ... x*y] 36 ''' 37 # May course some overlap if the shape(row/column) is different 38 ax1 = fig.add_subplot(2, 2, 1) 39 ax2 = fig.add_subplot(2, 2, 2) 40 ax4 = fig.add_subplot(2, 2, 4) 41 ax3 = plt.subplot(2, 2, 3) 42 43 ax1.plot(np.random.randint(1, 5, 5), np.arange(5)) 44 # Note np.arange(10)*3 will return an array shape(1, 10) with each element * 3 45 ax2.plot(np.arange(10)*3, np.arange(10)) 46 ax4.plot(np.random.randint(1, 10, 10), np.random.randint(1, 10, 10)) 47 48 month = curve['DATE'].dt.month 49 value = curve['VALUE'] 50 # If no new fig here, the curve will be plot on the latest fig(ax4 here) 51 fig = plt.figure(figsize=(9, 7)) 52 plt.plot(month[0:6], value[0:6], c='red', label='first half year') # c='r'/c=(1, 0, 0) 53 plt.plot(month[6:12], value[6:12], c='blue', label='second half year') 54 # If not call legend function, the label would not show 55 # loc='best' will place the label in a best location 56 ''' 57 loc : int or string or pair of floats, default: 'upper right' 58 The location of the legend. Possible codes are: 59 60 =============== ============= 61 Location String Location Code 62 =============== ============= 63 'best' 0 64 'upper right' 1 65 'upper left' 2 66 'lower left' 3 67 'lower right' 4 68 'right' 5 69 'center left' 6 70 'center right' 7 71 'lower center' 8 72 'upper center' 9 73 'center' 10 74 =============== ============= 75 ''' 76 plt.legend(loc='best') 77 plt.xlabel('Month') 78 plt.ylabel('Rate') 79 plt.title('My rate curve') 80 81 plt.show()
分段解釋
首先導入須要用到的 numpy 和 pandas 模塊,讀取所須要的數據,轉變爲指定的時間格式,
1 import pandas as pd 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 curve = pd.read_csv('curve.csv') 6 print(curve) 7 print('------------') 8 # Change format to datetime format 9 curve['DATE'] = pd.to_datetime(curve['DATE']) 10 print(curve)
輸出結果以下
DATE VALUE A B C D E 0 1/1/1948 3.4 2.400000 4.50 2.400000 2.200000 5.60 1 2/1/1948 3.8 2.700000 3.50 8.800000 3.400000 4.20 2 3/1/1948 4.2 2.500000 4.60 4.300000 4.100000 7.30 3 4/1/1948 5.1 2.633333 4.30 7.066667 5.133333 7.40 4 5/1/1948 1.9 2.683333 4.35 8.016667 6.083333 8.25 5 6/1/1948 2.4 2.733333 4.40 8.966667 7.033333 9.10 6 7/1/1948 3.2 2.783333 4.45 9.916667 7.983333 9.95 7 8/1/1948 4.4 2.833333 4.50 10.866667 8.933333 10.80 8 9/1/1948 5.2 2.883333 4.55 11.816667 9.883333 11.65 9 10/1/1948 3.2 2.933333 4.60 12.766667 10.833333 12.50 10 11/1/1948 2.1 2.983333 4.65 13.716667 11.783333 13.35 11 12/1/1948 1.2 3.033333 4.70 14.666667 12.733333 14.20 12 1/1/1949 5.5 3.083333 4.75 15.616667 13.683333 15.05 13 2/1/1949 3.2 3.133333 4.80 16.566667 14.633333 15.90 14 3/1/1949 6.2 3.183333 4.85 17.516667 15.583333 16.75 15 4/1/1949 1.3 3.233333 4.90 18.466667 16.533333 30.00 ------------ DATE VALUE A B C D E 0 1948-01-01 3.4 2.400000 4.50 2.400000 2.200000 5.60 1 1948-02-01 3.8 2.700000 3.50 8.800000 3.400000 4.20 2 1948-03-01 4.2 2.500000 4.60 4.300000 4.100000 7.30 3 1948-04-01 5.1 2.633333 4.30 7.066667 5.133333 7.40 4 1948-05-01 1.9 2.683333 4.35 8.016667 6.083333 8.25 5 1948-06-01 2.4 2.733333 4.40 8.966667 7.033333 9.10 6 1948-07-01 3.2 2.783333 4.45 9.916667 7.983333 9.95 7 1948-08-01 4.4 2.833333 4.50 10.866667 8.933333 10.80 8 1948-09-01 5.2 2.883333 4.55 11.816667 9.883333 11.65 9 1948-10-01 3.2 2.933333 4.60 12.766667 10.833333 12.50 10 1948-11-01 2.1 2.983333 4.65 13.716667 11.783333 13.35 11 1948-12-01 1.2 3.033333 4.70 14.666667 12.733333 14.20 12 1949-01-01 5.5 3.083333 4.75 15.616667 13.683333 15.05 13 1949-02-01 3.2 3.133333 4.80 16.566667 14.633333 15.90 14 1949-03-01 6.2 3.183333 4.85 17.516667 15.583333 16.75 15 1949-04-01 1.3 3.233333 4.90 18.466667 16.533333 30.00
繪製折線圖
1 # matplotlib inline 2 # If plot nothing and show, it will plot and show a blank board 3 # plt.plot() 4 # plt.show() 5 # Similar to pyqtgraph, plot(x_list, y_list) 6 plt.plot(curve['DATE'], curve['VALUE']) 7 # If the tick is too long, use rotation to adjust 8 plt.xticks(rotation=-45) 9 plt.xlabel('Month') 10 plt.ylabel('Rate') 11 plt.title('Unemployment Rate') 12 #plt.show()
顯示圖形
接着繪製帶有子圖的折線圖
其中子圖的順序如代碼中註釋所示
1 # Sub figure 2 # figsize decide the size of figure window 3 fig = plt.figure('figure_name', figsize=(7, 7)) 4 # add_subplot(row, column, location) 5 # add_subplot will divide fig into several part(according to row and column) and place the subplot in input location 6 ''' fig divided like that: 7 [1 ... x 8 . . 9 . . 10 . . 11 y ... x*y] 12 ''' 13 # May course some overlap if the shape(row/column) is different 14 ax1 = fig.add_subplot(2, 2, 1) 15 ax2 = fig.add_subplot(2, 2, 2) 16 ax4 = fig.add_subplot(2, 2, 4) 17 ax3 = plt.subplot(2, 2, 3) 18 19 ax1.plot(np.random.randint(1, 5, 5), np.arange(5)) 20 # Note np.arange(10)*3 will return an array shape(1, 10) with each element * 3 21 ax2.plot(np.arange(10)*3, np.arange(10)) 22 ax4.plot(np.random.randint(1, 10, 10), np.random.randint(1, 10, 10))
顯示圖形
最後,嘗試將兩條折線繪製在同一個圖上,
Note: 第四行生成了一個新的fig,若是此處沒有新生成一個fig,則圖像會被顯示在最近的一個fig上(此處爲以前的ax4)
1 month = curve['DATE'].dt.month 2 value = curve['VALUE'] 3 # If no new fig here, the curve will be plot on the latest fig(ax4 here) 4 fig = plt.figure(figsize=(9, 7)) 5 plt.plot(month[0:6], value[0:6], c='red', label='first half year') # c='r'/c=(1, 0, 0) 6 plt.plot(month[6:12], value[6:12], c='blue', label='second half year') 7 # If not call legend function, the label would not show 8 # loc='best' will place the label in a best location 9 ''' 10 loc : int or string or pair of floats, default: 'upper right' 11 The location of the legend. Possible codes are: 12 13 =============== ============= 14 Location String Location Code 15 =============== ============= 16 'best' 0 17 'upper right' 1 18 'upper left' 2 19 'lower left' 3 20 'lower right' 4 21 'right' 5 22 'center left' 6 23 'center right' 7 24 'lower center' 8 25 'upper center' 9 26 'center' 10 27 =============== ============= 28 ''' 29 plt.legend(loc='best') 30 plt.xlabel('Month') 31 plt.ylabel('Rate') 32 plt.title('My rate curve') 33 34 plt.show()
顯示圖形
完整代碼
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import numpy as np 4 5 curve = pd.read_csv('curve.csv') 6 cols = ['A', 'B', 'C', 'D', 'E'] 7 para = curve[cols] 8 print(para) 9 print(para[:1]) 10 print('-----------') 11 # ix function can fetch the data in certain position by index 12 # ix[row, column], row/column can be a number/list/key_list 13 # Bar height decide the height of bar graph 14 bar_height = para.ix[0, cols].values # para.ix[0, cols] type is Series 15 # Bar position decide the x distance to base point 16 bar_position = np.arange(5) + 1 17 # subplots function return a figure and only one subplot 18 # fig to set figure style, ax(axis) for graph draw 19 fig, ax = plt.subplots() 20 # bar(position_list, height_list, width_of_bar) 21 ax.bar(bar_position, bar_height, 0.3) 22 # Use barh to create a horizonal bar figure 23 ax.barh(bar_position, bar_height, 0.3) 24 # Set position of ticks 25 ax.set_xticks(range(1, 6)) 26 # Set x tick labels name and rotation 27 ax.set_xticklabels(cols, rotation=45) 28 # Set x/y label name 29 ax.set_xlabel('Type') 30 ax.set_ylabel('Rate') 31 ax.set_title('This is a test figure')
分段解釋
首先導入各個模塊,並讀取數據,
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import numpy as np 4 5 curve = pd.read_csv('curve.csv') 6 cols = ['A', 'B', 'C', 'D', 'E'] 7 para = curve[cols] 8 print(para) 9 print(para[:1]) 10 print('-----------')
輸出結果爲
A B C D E 0 2.400000 4.50 2.400000 2.200000 5.60 1 2.700000 3.50 8.800000 3.400000 4.20 2 2.500000 4.60 4.300000 4.100000 7.30 3 2.633333 4.30 7.066667 5.133333 7.40 4 2.683333 4.35 8.016667 6.083333 8.25 5 2.733333 4.40 8.966667 7.033333 9.10 6 2.783333 4.45 9.916667 7.983333 9.95 7 2.833333 4.50 10.866667 8.933333 10.80 8 2.883333 4.55 11.816667 9.883333 11.65 9 2.933333 4.60 12.766667 10.833333 12.50 10 2.983333 4.65 13.716667 11.783333 13.35 11 3.033333 4.70 14.666667 12.733333 14.20 12 3.083333 4.75 15.616667 13.683333 15.05 13 3.133333 4.80 16.566667 14.633333 15.90 14 3.183333 4.85 17.516667 15.583333 16.75 15 3.233333 4.90 18.466667 16.533333 30.00 A B C D E 0 2.4 4.5 2.4 2.2 5.6 -----------
隨後根據數據繪製柱狀圖
1 # ix function can fetch the data in certain position by index 2 # ix[row, column], row/column can be a number/list/key_list 3 # Bar height decide the height of bar graph 4 bar_height = para.ix[0, cols].values # para.ix[0, cols] type is Series 5 # Bar position decide the x distance to base point 6 bar_position = np.arange(5) + 1 7 # subplots function return a figure and only one subplot 8 # fig to set figure style, ax(axis) for graph draw 9 fig, ax = plt.subplots() 10 # bar(position_list, height_list, width_of_bar) 11 ax.bar(bar_position, bar_height, 0.3) 12 # Use barh to create a horizonal bar figure 13 ax.barh(bar_position, bar_height, 0.3) 14 # Set position of ticks 15 ax.set_xticks(range(1, 6)) 16 # Set x tick labels name and rotation 17 ax.set_xticklabels(cols, rotation=45) 18 # Set x/y label name 19 ax.set_xlabel('Type') 20 ax.set_ylabel('Rate') 21 ax.set_title('This is a test figure')
獲得圖形
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import numpy as np 4 5 curve = pd.read_csv('curve.csv') 6 cols = ['A', 'B', 'C', 'D', 'E'] 7 8 fig, ax = plt.subplots() 9 ax.boxplot(curve[cols].values) # curve[cols].values is ndarray 10 print(curve[cols].values) 11 plt.show()
輸出數據
[[ 2.4 4.5 2.4 2.2 5.6 ] [ 2.7 3.5 8.8 3.4 4.2 ] [ 2.5 4.6 4.3 4.1 7.3 ] [ 2.63333333 4.3 7.06666667 5.13333333 7.4 ] [ 2.68333333 4.35 8.01666667 6.08333333 8.25 ] [ 2.73333333 4.4 8.96666667 7.03333333 9.1 ] [ 2.78333333 4.45 9.91666667 7.98333333 9.95 ] [ 2.83333333 4.5 10.86666667 8.93333333 10.8 ] [ 2.88333333 4.55 11.81666667 9.88333333 11.65 ] [ 2.93333333 4.6 12.76666667 10.83333333 12.5 ] [ 2.98333333 4.65 13.71666667 11.78333333 13.35 ] [ 3.03333333 4.7 14.66666667 12.73333333 14.2 ] [ 3.08333333 4.75 15.61666667 13.68333333 15.05 ] [ 3.13333333 4.8 16.56666667 14.63333333 15.9 ] [ 3.18333333 4.85 17.51666667 15.58333333 16.75 ] [ 3.23333333 4.9 18.46666667 16.53333333 30. ]]
顯示圖形
1 import matplotlib.pyplot as plt 2 import numpy as np 3 import pandas as pd 4 5 curve = pd.read_csv('curve.csv') 6 fig, ax = plt.subplots() 7 # scatter(x, y) x for x axis para list/Series, y for y axis para list/Series 8 ax.scatter(curve['A'], curve['B']) 9 plt.show()
輸出圖形
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import numpy as np 4 5 curve = pd.read_csv('curve.csv') 6 cols = ['A', 'B', 'C', 'D', 'E'] 7 # value_counts function will return the number of each value 8 print(curve['C'].value_counts()) 9 fig, ax = plt.subplots() 10 # hist(Series, range=, bins=) 11 # Series is the data to be plotted, range is the plot range, bins is the number of plot hists in range 12 ax.hist(curve['C'], range=(1,20), bins=20) 13 # Set the x/y axis limit range 14 ax.set_xlim(0, 20) 15 ax.set_ylim(0, 5) 16 plt.show()
輸出結果
15.616667 1
18.466667 1
12.766667 1
8.800000 1
2.400000 1
16.566667 1
9.916667 1
8.016667 1
10.866667 1
17.516667 1
7.066667 1
4.300000 1
11.816667 1
8.966667 1
14.666667 1
13.716667 1
Name: C, dtype: int64
顯示圖形
利用matplotlib還能夠對圖形的細節進行相應的設置
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import numpy as np 4 5 curve = pd.read_csv('curve.csv') 6 7 fig, ax = plt.subplots() 8 9 # Hide the tick params 10 ax.tick_params(bottom='off', top='off', left='off', right='off') 11 # Hide spine 12 print(type(ax.spines)) 13 for key, spine in ax.spines.items(): 14 print(key, spine) 15 spine.set_visible(False) 16 # Set the color, (R, G, B) the value should be between (0, 1) 17 color_dark_blue = (0/255, 107/255, 164/255) 18 color_orange = (255/255, 128/255, 14/255) 19 ax.plot(curve['A'], curve['B'], c=color_dark_blue, label='AB', linewidth=7) 20 ax.plot(curve['C'], curve['D'], c=color_orange, label='CD', linewidth=7) 21 plt.legend(loc='upper right') 22 plt.show()
輸出圖形
相關閱讀
1. numpy 的使用
2. pandas 的使用