1. 程式人生 > >Python學習筆記——資料分析之Matplotlib繪圖

Python學習筆記——資料分析之Matplotlib繪圖

目錄

Matplotlib 是一個 Python 的 2D繪相簿,通過 Matplotlib,開發者可以僅需要幾行程式碼,便可以生成繪圖,直方圖,功率譜,條形圖,錯誤圖,散點圖等。

  • 用於創建出版質量圖表的繪圖工具庫

  • 目的是為Python構建一個Matlab式的繪圖介面

  • import matplotlib.pyplot as plt

  • pyploy模組包含了常用的matplotlib API函式

figure

  • Matplotlib的影象均位於figure物件中

  • 建立figure:fig = plt.figure()

示例程式碼:

# 引入matplotlib包
import matplotlib.pyplot as plt
import numpy as np

%matplotlib inline #在jupyter notebook 裡需要使用這一句命令

# 建立figure物件
fig = plt.figure()

執行結果:

<matplotlib.figure.Figure at 0x11a2dd7b8>

subplot

fig.add_subplot(a, b, c)

  • a,b 表示將fig分割成 a*b 的區域

  • c 表示當前選中要操作的區域,

  • 注意:從1開始編號(不是從0開始)

  • plot 繪圖的區域是最後一次指定subplot的位置 (jupyter notebook裡不能正確顯示)

示例程式碼:

# 指定切分割槽域的位置
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)

# 在subplot上作圖
random_arr = np.random.randn(100)
#print random_arr

# 預設是在最後一次使用subplot的位置上作圖,但是在jupyter notebook 裡可能顯示有誤
plt.plot(random_arr)

# 可以指定在某個或多個subplot位置上作圖
# ax1 = fig.plot(random_arr)
# ax2 = fig.plot(random_arr)
# ax3 = fig.plot(random_arr)

# 顯示繪圖結果
plt.show()

執行結果:

折線圖:以折線的上升或下降來表示統計數量的增減變化的統計

特點:能夠顯示資料的變化趨勢,反映事物的變化情況(變化)

直方圖:一系列高度不等的縱向條紋或線段表示資料分佈的情況。

一般用橫軸表示資料範圍,縱軸表示分佈情況

特點:繪製連續性的資料,展示一組或者多組資料的分佈狀況(統計)

條形圖:排列在工作表的列或行中的資料可以繪製到條形圖中

特點:繪製離散的資料,能夠一眼看出各個資料的大小,比較資料之間的差別(統計)

散點圖:用兩組資料構成多個座標點,考察座標點的分佈,判斷兩變數

之間是否存在某種關聯或總結座標點的分佈模式

特點:判斷變數之間是否存在數量關聯趨勢,展示離群點(分佈規律)

直方圖:hist

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

plt.hist(np.random.randn(100), bins=10, color='b', alpha=0.3)
plt.show()

執行結果:


散點圖:scatter

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

# 繪製散點圖
x = np.arange(50)
y = x + 5 * np.random.rand(50)
plt.scatter(x, y)
plt.show()

執行結果: 

柱狀圖:bar

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

# 柱狀圖
x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
ax = plt.subplot(1,1,1)
ax.bar(x, y1, width, color='r')
ax.bar(x+width, y2, width, color='g')
ax.set_xticks(x+width)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
plt.show()

執行結果:

矩陣繪圖:plt.imshow()

  • 混淆矩陣,三個維度的關係

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

# 矩陣繪圖
m = np.random.rand(10,10)
print(m)
plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
plt.show()

執行結果:

[[ 0.92859942  0.84162134  0.37814667  0.46401549  0.93935737  0.0344159
   0.56358375  0.75977745  0.87983192  0.22818774]
 [ 0.88216959  0.43369207  0.1303902   0.98446182  0.59474031  0.04414217
   0.86534444  0.34919228  0.53950028  0.89165269]
 [ 0.52919761  0.87408715  0.097871    0.78348534  0.09354791  0.3186
   0.25978432  0.48340623  0.1107699   0.14065592]
 [ 0.90834516  0.42377475  0.73042695  0.51596826  0.14154431  0.22165693
   0.64705882  0.78062873  0.55036304  0.40874584]
 [ 0.98853697  0.46762114  0.69973423  0.7910757   0.63700306  0.68793919
   0.28685306  0.3473426   0.17011744  0.18812329]
 [ 0.73688943  0.58004874  0.03146167  0.08875797  0.32930191  0.87314734
   0.50757536  0.8667078   0.8423364   0.99079049]
 [ 0.37660356  0.63667774  0.78111565  0.25598593  0.38437628  0.95771051
   0.01922366  0.37020219  0.51020305  0.05365718]
 [ 0.87588452  0.56494761  0.67320078  0.46870376  0.66139913  0.55072149
   0.51328222  0.64817353  0.198525    0.18105368]
 [ 0.86038137  0.55914088  0.55240021  0.15260395  0.4681218   0.28863395
   0.6614597   0.69015592  0.46583629  0.15086562]
 [ 0.01373772  0.30514083  0.69804049  0.5014782   0.56855904  0.14889117
   0.87596848  0.29757133  0.76062891  0.03678431]]

plt.subplots()

  • 同時返回新建立的figuresubplot物件陣列

  • 生成2行2列subplot:fig, subplot_arr = plt.subplots(2,2)

  • 在jupyter裡可以正常顯示,推薦使用這種方式建立多個圖表

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

fig, subplot_arr = plt.subplots(2,2)
# bins 為顯示個數,一般小於等於數值個數
subplot_arr[1,0].hist(np.random.randn(100), bins=10, color='b', alpha=0.3)
plt.show()

執行結果: 

顏色、標記、線型

  • ax.plot(x, y, ‘r--’)

等價於ax.plot(x, y, linestyle=‘--’, color=‘r’)

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2)
axes[0].plot(np.random.randint(0, 100, 50), 'ro--')
# 等價
axes[1].plot(np.random.randint(0, 100, 50), color='r', linestyle='dashed', marker='o')

執行結果:

[<matplotlib.lines.Line2D at 0x11a901e80>]

  • 常用的顏色、標記、線型

刻度、標籤、圖例

  • 設定刻度範圍

    plt.xlim(), plt.ylim()

    ax.set_xlim(), ax.set_ylim()

  • 設定顯示的刻度

    plt.xticks(), plt.yticks()

    ax.set_xticks(), ax.set_yticks()

  • 設定刻度標籤

    ax.set_xticklabels(), ax.set_yticklabels()

  • 設定座標軸標籤

    ax.set_xlabel(), ax.set_ylabel()

  • 設定標題

    ax.set_title()

  • 圖例

    ax.plot(label=‘legend’)

    ax.legend(), plt.legend()

    loc=‘best’:自動選擇放置圖例最佳位置

示例程式碼:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1)
ax.plot(np.random.randn(1000).cumsum(), label='line0')

# 設定刻度
#plt.xlim([0,500])
ax.set_xlim([0, 800])

# 設定顯示的刻度
#plt.xticks([0,500])
ax.set_xticks(range(0,500,100))

# 設定刻度標籤
ax.set_yticklabels(['Jan', 'Feb', 'Mar'])

# 設定座標軸標籤
ax.set_xlabel('Number')
ax.set_ylabel('Month')

# 設定標題
ax.set_title('Example')

# 圖例
ax.plot(np.random.randn(1000).cumsum(), label='line1')
ax.plot(np.random.randn(1000).cumsum(), label='line2')
ax.legend()
ax.legend(loc='best')
#plt.legend()

執行結果: <matplotlib.legend.Legend at 0x11a4061d0> 

matplotlib基本要點

設定圖片大小

調整X或者Y軸上的刻度

設定中文顯示

為什麼無法顯示中文:

matplotlib預設不支援中文字元,因為預設的英文字型無法顯示漢字


檢視linux/mac下面支援的字型:

fc-list   à檢視支援的字型

fc-list :lang=zh à檢視支援的中文(冒號前面有空格)

那麼問題來了:如何修改matplotlib的預設字型?

       通過matplotlib.rc可以修改,具體方法參見原始碼(windows/linux)

   通過matplotlib 下的font_manager可以解決(windows/linux/mac)

給影象新增描述資訊


自定義繪製圖形的風格

為每條線新增圖例