對於Python數據可視化庫,matplotlib 已經成爲事實上的數據可視化方面最主要的庫,此外還有不少其餘庫,例如vispy,bokeh, seaborn,pyga,folium 和 networkx,這些庫有些是構建在 matplotlib 之上,還有些有其餘一些功能。 html
目錄 python
matplotlibide
matplotlib 是一個基於 Python 的 2D 繪圖庫,其能夠在跨平臺的在各類硬拷貝格式和交互式環境中繪製出高圖形。Matplotlib 可以建立多數類型的圖表,如條形圖,散點圖,條形圖,餅圖,堆疊圖,3D 圖和地圖圖表。函數
%matplotlib 命令能夠在當前的 Notebook 中啓用繪圖。Matlibplot 提供了多種繪圖 UI ,可進行以下分類 :佈局
安裝Matplotlib命令:pip install matplotlib字體
基本函數編碼
legend:增長圖例(線的標題) ,格式:plt.legend(handles=(line1, line2, line3),labels=('label1', 'label2', 'label3'),loc='upper right'), 見以下示例代碼spa
1 ln1, = plt.plot(x_data, y_data, color = 'red', linewidth = 2.0, linestyle = '--') 2 ln2, = plt.plot(x_data, y_data2, color = 'blue', linewidth = 3.0, linestyle = '-.') 3 plt.legend(handles=[ln2, ln1], labels=['Android基礎', 'Java基礎'], loc='lower right')
loc參數值:.net
figure:新建一個畫布,格式:figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)3d
spines:在matplotlib的圖中,默認有四個軸,兩個橫軸和兩個豎軸,能夠經過ax = plt.gca()方法獲取,gca是‘get current axes’的縮寫,獲取圖像的軸,總共有四個軸 top、bottom、left、right
示例代碼:
1 import matplotlib.pyplot as plt 2
3 fig = plt.figure(figsize=(4, 3), frameon=True, facecolor='r') 4 ax = fig.add_subplot(1, 1, 1) 5 ax.spines['top'].set_color = 'none'
6 ax.spines['right'].set_color = 'none'
7 ax.spines['left'].set_position(('data', 0)) 8 ax.spines['bottom'].set_position(('data', 0)) 9 plt.show()
效果圖:
中文亂碼
1 from pylab import mpl 2
3 mpl.rcParams['font.sans-serif'] = 'FangSong' # 指定默認字體
4 mpl.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示爲方塊的問題
Windows的字體對應名稱以下
plot:線性圖
格式:plt.plot(x,y,format_string,**kwargs)
示例:
1 import matplotlib.pyplot as plt 2 from pylab import mpl 3
4 mpl.rcParams['font.sans-serif'] = 'FangSong' # 指定默認字體
5 mpl.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示爲方塊的問題
6
7 year = ['1950', '1960', '1970', '1980', '1990', '2000', '2010'] 8 gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10298.7, 14958.3] 9 y_data = [100, 200, 300, 400, 500, 600, 700] 10
11
12 def draw_plot(): 13 # plt.plot(year, gdp, 'go-', year, y_data, 'rp:')
14 plt.plot(year, gdp, 'go-', label='gdp') 15 plt.plot(year, y_data, 'rp:', label='second line') 16 plt.title("plot 線圖demo") 17 plt.xlabel('年度') 18 plt.ylabel('gdp') 19 plt.legend() #生成默認圖例
20 plt.show()
效果圖:
bar:柱狀圖
格式:bar(left, height, width, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3)
示例
1 def draw_bar(): 2 plt.bar(x=year, height=gdp, width=0.4, label='gdp', color='green') 3 plt.bar(x=year, height=y_data, width=0.4, label='secend', color='red') 4 # 在柱狀圖上顯示具體數值, ha參數控制水平對齊方式, va控制垂直對齊方式
5 for x, y in enumerate(y_data): 6 plt.text(x, y - 400, '%s' % y, ha='center', va='bottom') 7 for x, y in enumerate(gdp): 8 plt.text(x, y + 400, '%s' % y, ha='center', va='top') 9
10 plt.title("bar 條形圖") 11 plt.xlabel('年度') 12 plt.ylabel('gdp') 13 plt.legend() 14 plt.show()
效果圖:
使用 bar() 函數繪製柱狀圖時,默認不會在柱狀圖上顯示具體的數值。爲了能在柱狀圖上顯示具體的數值,程序能夠調用 text() 函數在數據圖上輸出文字,增長以下代碼:1for x, y in enumerate(y_data):
1 for x, y in enumerate(y_data): 2 plt.text(x, y - 400, '%s' % y, ha='center', va='bottom') 3 for x, y in enumerate(gdp): 4 plt.text(x, y + 400, '%s' % y, ha='center', va='top')
效果圖:
如上圖 所示的顯示效果來看柱狀圖重疊,爲了實現條柱井列顯示的效果,首先分析條柱重疊在一塊兒的緣由。使用 Matplotlib 繪製柱狀圖時一樣也須要 X 軸數據,本程序的 X 軸數據是元素爲字符串的 list 列表,所以程序實際上使用各字符串的索引做爲 X 軸數據。好比 '1950' 字符串位於列表的第一個位置,所以表明該條柱的數據就被繪製在 X 軸的刻度值1處(因爲兩個柱狀圖使用了相同的 X 軸數據,所以它們的條柱徹底重合在一塊兒)。爲了將多個柱狀圖的條柱並列顯示,程序須要爲這些柱狀圖從新計算不一樣的 X 軸數據。爲了精確控制條柱的寬度,程序能夠在調用 bar() 函數時傳入 width 參數,這樣能夠更好地計算條柱的並列方式。
示例 :
1 def draw_bar2(): 2 barwidth=0.4
3 plt.bar(x=range(len(year)), height=gdp, width=0.4, label='gdp', color='green') 4 plt.bar(x=np.arange(len(year)) + barwidth, height=y_data, width=0.4, label='secend', color='red') 5 # 在柱狀圖上顯示具體數值, ha參數控制水平對齊方式, va控制垂直對齊方式
6 for x, y in enumerate(gdp): 7 plt.text(x, y + 400, '%s' % y, ha='center', va='top') 8 for x, y in enumerate(y_data): 9 plt.text(x + barwidth, y + 400, '%s' % y, ha='center', va='top') 10
11 plt.title("bar 條形圖") 12 plt.xlabel('年度') 13 plt.ylabel('gdp') 14 plt.legend() 15 plt.show()
效果圖:
運行上面程序,將會發現該柱狀圖的 X 軸的刻度值變成 0、一、2 等值,再也不顯示年份。爲了讓柱狀圖的 X 軸的刻度值顯示年份,程序能夠調用 xticks() 函數從新設置 X 軸的刻度值,以下:
但願兩個條柱之間有一點縫隙,那麼程序只要對第二個條柱的 X 軸數據略作修改便可,完整代碼以下:
1 def draw_bar2(): 2 barwidth=0.4
3 plt.bar(x=range(len(year)), height=gdp, width=barwidth, label='gdp', color='green') 4 plt.bar(x=np.arange(len(year)) + barwidth + 0.01, height=y_data, width=barwidth, label='secend', color='red') 5 # 在柱狀圖上顯示具體數值, ha參數控制水平對齊方式, va控制垂直對齊方式
6 for x, y in enumerate(gdp): 7 plt.text(x, y + 400, '%s' % y, ha='center', va='top') 8 for x, y in enumerate(y_data): 9 plt.text(x + barwidth + 0.01, y + 400, '%s' % y, ha='center', va='top') 10
11 #X軸添加刻度
12 plt.xticks(np.arange(len(year)) + barwidth/2 + 0.01, year) 13 plt.title("bar 條形圖") 14 plt.xlabel('年度') 15 plt.ylabel('gdp') 16 plt.legend() 17 plt.show()
效果圖:
barh:水平柱狀圖
barh() 函數的用法與 bar() 函數的用法基本同樣,只是在調用 barh() 函數時使用 y參數傳入 Y 軸數據,使用 width 參數傳入表明條柱寬度的數據。
示例:
1 def draw_barh(): 2 barwidth = 0.4
3 plt.barh(y=range(len(year)), width=gdp, height=barwidth, label='gdp', color='green') 4 plt.barh(y=np.arange(len(year)) + barwidth + 0.01, width=y_data, height=barwidth, label='secend', color='red') 5 # 在柱狀圖上顯示具體數值, ha參數控制水平對齊方式, va控制垂直對齊方式
6 for y, x in enumerate(gdp): 7 plt.text(x + 1000, y + barwidth/2, '%s' % x, ha='center', va='bottom') 8 for y, x in enumerate(y_data): 9 plt.text(x + 1400, y + barwidth/2 - 0.01, '%s' % x, ha='center', va='top') 10
11 # y軸添加刻度
12 plt.yticks(np.arange(len(year)) + barwidth / 2 + 0.01, year) 13 plt.title("barh 水平柱狀圖") 14 plt.xlabel('gdp') 15 plt.ylabel('年度') 16 plt.legend() 17 plt.show()
效果圖:
pie:餅圖
格式:pie(x, explode=None, labels=None, colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'), autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center = (0, 0), frame = False )
示例
1 def draw_pie(): 2 plt.pie(x=gdp, 3 labels=year, 4 autopct='%.3f%%', 5 explode=[0, 0, 0, 0.03, 0, 0, 0]) 6
7 plt.title("pie 圖") 8 plt.show()
效果:
scatter:散點圖
格式:scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
示例:
1 def draw_catter(): 2 plt.scatter(x=year, y=gdp, c='red', marker='*', s=100) 3
4 plt.title("catter 散點圖") 5 plt.show()
效果:
hist:直方圖
柱狀圖與直方圖:
格式:pyplot.hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
函數返回值:
stackplot:面積圖
格式:stackplot(x, *args, labels=(), colors=None, baseline='zero', data=None, **kwargs)
示例 :
1 plt.stackplot(year, gdp, y_data, colors=['r', 'g']) 2 plt.title("stackplot 面積圖") 3 plt.show()
效果:
從圖上看不出顏色表明的含義,增長圖例,完整代碼以下:
1 def draw_stackplot(): 2 plt.plot([], [], color='r', label='gdp', linewidth=5) 3 plt.plot([], [], color='g', label='y_data', linewidth=5) 4 plt.stackplot(year, gdp, y_data, colors=['r', 'g']) 5 plt.title("stackplot 面積圖") 6 plt.legend() 7 plt.show()
效果圖:
subplot:子圖佈局
subplot 在一張數據圖上包含多個子圖,格式:subplot(nrows, ncols, index, **kwargs)
subplot() 函數也支持直接傳入一個三位數的參數,其中第一位數將做爲 nrows 參數;第二位數將做爲 ncols 參數;第三位數將做爲 index 參數。
示例:
1 def draw_subplot(): 2 plt.figure(figsize=(4, 3)) 3
4 x_data = np.linspace(-np.pi, np.pi, 64, endpoint=True) 5 plt.subplot(2, 1, 1) 6 plt.plot(x_data, np.sin(x_data)) 7 plt.gca().spines['top'].set_color('none') 8 plt.gca().spines['right'].set_color('none') 9 plt.gca().spines['left'].set_position(('data', 0)) 10 plt.gca().spines['bottom'].set_position(('data', 0)) 11 plt.title('sin') 12
13 plt.subplot(2, 2, 3) 14 plt.plot(x_data, np.cos(x_data)) 15 plt.gca().spines['top'].set_color('none') 16 plt.gca().spines['right'].set_color('none') 17 plt.gca().spines['left'].set_position(('data', 0)) 18 plt.gca().spines['bottom'].set_position(('data', 0)) 19 plt.title('cos') 20
21 plt.subplot(2, 2, 4) 22 plt.plot(x_data, np.tan(x_data)) 23 plt.gca().spines['top'].set_color('none') 24 plt.gca().spines['right'].set_color('none') 25 plt.gca().spines['left'].set_position(('data', 0)) 26 plt.gca().spines['bottom'].set_position(('data', 0)) 27 plt.title('tan') 28
29 plt.show()
效果:
GridSpec:網格佈局
指定在給定GridSpec中的子圖位置
示例:
1 def draw_gridspace(): 2 plt.figure(figsize=(4, 3)) 3
4 x_data = np.linspace(-np.pi, np.pi, 64, endpoint=True) 5 gs = gridspace.GridSpec(2, 2) 6 ax1 = plt.subplot(gs[0, :]) 7 ax2 = plt.subplot(gs[1, 0]) 8 ax3 = plt.subplot(gs[1, 1]) 9
10 ax1.plot(x_data, np.sin(x_data)) 11 ax1.spines['top'].set_color('none') 12 ax1.spines['right'].set_color('none') 13 ax1.spines['left'].set_position(('data', 0)) 14 ax1.spines['bottom'].set_position(('data', 0)) 15 ax1.set_title('sin') 16
17 ax2.plot(x_data, np.cos(x_data)) 18 ax2.spines['top'].set_color('none') 19 ax2.spines['right'].set_color('none') 20 ax2.spines['left'].set_position(('data', 0)) 21 ax2.spines['bottom'].set_position(('data', 0)) 22 ax2.set_title('cos') 23
24 ax3.plot(x_data, np.tan(x_data)) 25 ax3.spines['top'].set_color('none') 26 ax3.spines['right'].set_color('none') 27 ax3.spines['left'].set_position(('data', 0)) 28 ax3.spines['bottom'].set_position(('data', 0)) 29 ax3.set_title('tan') 30
31 plt.show()
效果與上節 subplot 一致
參考資料