Matplotlib之pyplot在數據分析中的常用操作

做機器學習方向首先得學會點Matplotlib庫的知識吧,所以我就在這做一下學習筆記,記錄一下我在機器學習方向上所常用到的Matplotlib上的知識。

官方文檔:網址http://matplotlib.org/api/pyplot_api.html#matplotlib後面加.pyplot.函數名便可查詢對應的函數用法。

一、折線圖的繪製

先上一個樣例代碼:

import matplotlib.pyplot as plt

plt.plot()
plt.show()

輸出結果:
0
這樣我們就畫了一個空白的圖像。

然後我們再嘗試着加入數據,畫二維座標圖首先需要一組二維數對(x, y),這裏我隨便找了一組數據作爲折線圖的x軸和y軸:

x_axis = [794.28818799999999,
         808.50958700000001,
         826.25461900000005,
         833.53230499999995,
         841.97451199999989,
         846.94015999999999,
         851.69061199999987,
         861.97213299999999,
         874.92434100000003,
         888.51824600000009]
y_axis = [79.877565000000004,
         99.524317000000011,
         62.525946999999995,
         57.281737,
         52.371316,
         70.615566000000001,
         47.351207000000002,
         43.719923000000001,
         40.642712000000003,
         38.535789000000001]

然後使用plt.plot()繪製折線圖:

plt.plot(x_axis, y_axis)
plt.show()

輸出結果如下:
1

接下來我們進一步對圖像進行細節處理:

plt.plot(x_axis, y_axis)
plt.xticks(rotation = 45)   #加入這條代碼
plt.show()

輸出結果(注意x軸座標的變化,數字傾斜了45°):
2
這樣一來,如果遇到x軸位數過長以至於重疊的時候,斜着畫x軸的方法就派上用場了。當然了,同理把xticks 換成yticks 就是改變y軸座標的傾斜度了。

接下來我們再給這個圖像加上“軸的說明”和一個“標題”。
代碼如下:

plt.plot(x_axis, y_axis)
plt.xticks(rotation = 45)

#新加入的代碼如下:
plt.xlabel("this is x_axis") #x軸說明
plt.ylabel("this is y_axis") #y軸說明
plt.title("this is title") #此圖像的標題

plt.show()

輸出結果:
3
這樣,我們就添加了x座標軸和y座標軸的含義以及這個圖像的意義。

那麼如果我想在同一個圖中同時畫兩條折線呢?那就寫plt.plot()兩次唄:
既然是兩條線,那就肯定再需要一組數據,這裏我們就在前面的數據上每個y座標軸值+1獲得一組新數據,代碼如下:

#再構造一組數據
x1_axis = x_axis.copy()
y1_axis = []
for i in y_axis:
    y1_axis.append(i+10)

有了數據就可以畫圖了,代碼如下:

plt.plot(x_axis, y_axis, c = "r", label = "red")
plt.plot(x1_axis, y1_axis, c = "b", label = "red")
plt.legend(loc = "best")

plt.show()

輸出結果:
7
下面我們來解釋以下,新增的代碼含義。

  1. 首先是plt.plot()中的參數c,這個是用來選擇曲線顏色的,比如”r”表示”red”, “b”表示”blue”等等;
  2. 其次是參數label,表示的是這條曲線的含義,就是上圖中右上角那個小框框裏面的解釋;
  3. 最後是函數plt.legend(loc = "best")就是用來表示這個小框框應該放在哪裏,裏面的參數loc的值可以是'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right','center left', 'center right', 'lower center', 'upper center', 'center',分別表示“最好位置”,“右上角”,“左上角”等等。

小結,以上全部的常用操作代碼列舉如下:

import matplotlib.pyplot as plt

#構造數據
x_axis = [794.28818799999999,
         808.50958700000001,
         826.25461900000005,
         833.53230499999995,
         841.97451199999989,
         846.94015999999999,
         851.69061199999987,
         861.97213299999999,
         874.92434100000003,
         888.51824600000009]
y_axis = [79.877565000000004,
         99.524317000000011,
         62.525946999999995,
         57.281737,
         52.371316,
         70.615566000000001,
         47.351207000000002,
         43.719923000000001,
         40.642712000000003,
         38.535789000000001]
#再構造一組數據
x1_axis = x_axis.copy()
y1_axis = []
for i in y_axis:
    y1_axis.append(i+10)

#繪圖
plt.plot(x_axis, y_axis, c = "r", label = "red")
plt.plot(x1_axis, y1_axis, c = "b", label = "red")

plt.xticks(rotation = 45)

plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")

plt.legend(loc = "best")

plt.show()

輸出結果:
11

二、子圖操作

有時候我們會在一個區域中畫很多個子圖,這就需要我們用到子圖操作了。
廢話不多說,先上代碼:

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax4 = fig.add_subplot(2,2,4)

plt.show()

輸出結果:
5
解釋一下上面的代碼,首先我們用函數plt.figure()創建了一個區域的對象;然後我們又用函數fig.add_subplot()在這個區域裏建了三個子圖,至於函數fig.add_subplot() 中的三個參數是什麼意思,我這裏用一張圖來說明就夠了:
4

下面我們再進一步對上面的圖像做一下進階處理:
代碼如下:

fig = plt.figure(figsize=(16,8)) #再添加此代碼

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,4)

#下面畫兩個折線圖,只對子圖1和子圖2填充數據
ax1.plot(x_axis, y_axis)
ax2.plot(x_axis, y_axis)

plt.show()

輸出結果:
6
明顯可以看到,這張圖像比上面那張寬了很多,高了也很多。plt.figure(figsize=(16,8)) 函數中的figsize參數就表示了這個區域的長和寬。

三、條形圖

條形圖也就是柱狀圖、bar形圖。

我們這裏只記錄一下數據分析中常用的操作,詳細具體的條形圖操作原理可以看一下這篇博客:
http://blog.sina.com.cn/s/blog_b09d4602010194wy.html

如圖,我們最終要畫一個類似這樣的條形圖:
12

首先,畫條形圖主要需要兩組數據:

  1. left:bar的位置;
  2. height:bar的高度值。

所謂的“bar的位置”就是指對應的每條bar在x軸上到0點的距離,“bar的高度值”就是指對應的每條bar(柱)在y座標軸對應的值。

我們先構造出這兩組數據:

bar_positions = [1, 2, 3, 4, 5, 6] #每條bar的位置
bar_heights = [2,3,6,1,7,8] #每條bar的高度值

然後繪製bar形圖:

import matplotlib.pyplot as plt

plt.bar(bar_positions, bar_heights, 0.3)
#這裏的第三個參數0.3的意思是bar的粗細

plt.show()

輸出結果:
14
由上面可知,條形圖的畫法和折線圖是相似的。

下面我們仿照上面的折線圖操作畫一下bar形圖,代碼如下:

import matplotlib.pyplot as plt

#構造數據
bar_positions = [i+0.9 for i in range(6)]
bar_heights = [2,3,6,1,7,8]
#再構造一組數據
bar_positions2 = [i+1.1 for i in range(6)]
bar_heights2 = bar_heights.copy()

#繪圖
plt.bar(bar_positions, bar_heights, 0.2, color = "r", label = "red")
plt.bar(bar_positions2, bar_heights2, 0.2, color = "b", label = "red")

#爲每條bar寫明含義
num_cols = ["first_bar", "second_bar", "third_bar", "forth_bar", "fifth_bar", "sixth_bar"]
plt.xticks(range(1,7), num_cols, rotation = 45)

plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")

plt.legend(loc = "best")

plt.show()

輸出結果:
12.5

還有一種條形圖,是橫着畫的,就是把函數plt.bar() 換成plt.barh() ,相應的bar的“位置”和“高度”對應着barh的“高度”和“寬度”,廢話不多說,上代碼:

import matplotlib.pyplot as plt

#構造數據
bar_positions = [1, 2, 3, 4, 5, 6]
bar_widths = [2,3,6,1,7,8]

#繪圖
plt.barh(bar_positions, bar_widths, 0.5)

#爲每條bar寫明含義
num_cols = ["first_bar", "second_bar", "third_bar", "forth_bar", "fifth_bar", "sixth_bar"]
plt.yticks(range(1,7), num_cols)

plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")

plt.legend(loc = "best")

plt.show()

輸出結果:
13.5

知識拓展:
下面我們用畫子圖的方法改進一下代碼,不過這裏我們使用的是另一種子圖操作,其實都差不多一樣,詳見官方文檔:
https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots

好了,先上代碼:

import matplotlib.pyplot as plt

#構造數據
bar_positions = [1, 2, 3, 4, 5, 6] 
bar_heights = [2,3,6,1,7,8] 

fig, ax = plt.subplots()
ax.bar(bar_positions, bar_heights, 0.5)
plt.show()

輸出結果:
13

接下來我們繼續進行圖像的進階操作,代碼如下:

import matplotlib.pyplot as plt

#構造數據
bar_positions = [1, 2, 3, 4, 5, 6] 
bar_heights = [2,3,6,1,7,8] 

num_cols = ["first_bar", "second_bar", "third_bar", "forth_bar", "fifth_bar", "sixth_bar"]

fig, ax = plt.subplots()

ax.bar(bar_positions, bar_heights, 0.5)

#爲每條bar寫明含義
ax.set_xticks(range(1,7))
ax.set_xticklabels(num_cols, rotation = 45)

ax.set_xlabel("this is x_axis")
ax.set_ylabel("this is y_axis")
ax.set_title("this is title")

plt.show()

輸出結果:
12

橫着畫也可以,代碼如下:

import matplotlib.pyplot as plt

#構造數據
bar_positions = [1, 2, 3, 4, 5, 6] 
bar_heights = [2,3,6,1,7,8] 

fig, ax = plt.subplots()

ax.barh(bar_positions, bar_widths, 0.5)#這裏把函數ax.bar()換成了ax.bar()
#下面在y座標軸上說明每條bar的含義
ax.set_yticks(range(1,7))
ax.set_yticklabels(num_cols, rotation = 45)

ax.set_xlabel("this is x_axis")
ax.set_ylabel("this is y_axis")
ax.set_title("this is title")

plt.show()

輸出結果:
112

四、散點圖

畫散點圖和折線圖差不多,只是把函數plot換成函數scatter(),當然了,散點圖也能進行子圖操作等等。

首先我們先畫一個簡單的散點圖,繼續使用上面的數據x_axis和y_axis:

#構造數據
x_axis = [794.28818799999999,
         808.50958700000001,
         826.25461900000005,
         833.53230499999995,
         841.97451199999989,
         846.94015999999999,
         851.69061199999987,
         861.97213299999999,
         874.92434100000003,
         888.51824600000009]
y_axis = [79.877565000000004,
         99.524317000000011,
         62.525946999999995,
         57.281737,
         52.371316,
         70.615566000000001,
         47.351207000000002,
         43.719923000000001,
         40.642712000000003,
         38.535789000000001]

然後開始繪製圖像:

import matplotlib.pyplot as plt

plt.scatter(x_axis, y_axis)
plt.show()

輸出結果:
11
進階操作:

import matplotlib.pyplot as plt

plt.scatter(x_axis, y_axis, marker='x', c='r', label = "red")
plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")
plt.xticks(rotation = 45)

plt.legend(loc = "upper right")

plt.show()

輸出結果:
222

至於子圖操作和畫折線圖差不多,這裏就不多囉嗦了。

五、直方圖

直方圖所用的函數就是plt.hist() 了。
直方圖一般用來統計一組數據中每個量的頻數。

統計學中直方圖定義如下:

對某一物理量在相同條件下做n次重複測量,得到一系列測量值,找出它的最大值和最小值,然後確定一個區間,使其包含全部測量數據,將區間分成若干小區間,統計測量結果出現在各小區間的頻數M,以測量數據爲橫座標,以頻數M爲縱座標,劃出各小區間及其對應的頻數高度,則可得到一個矩形圖,即統計直方圖。

# 隨便找了點數據
data = [2.7, 2.7, 2.8, 2.8, 2.9, 2.9, 2.9, 2.9, 2.9, 3.0, 3.0, 3.0, 3.0, 3.1, 3.1, 3.1, 3.2, 3.2, 3.2, 3.2, 3.2, 3.3, 3.3, 3.3, 3.3, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.8, 3.8, 3.8, 3.8, 3.8, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.4, 4.4, 4.4, 4.4, 4.4, 4.4, 4.4, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.6, 4.6, 4.6, 4.6, 4.8, 4.8, 4.8]

樣例代碼如下:

import matplotlib.pyplot as plt
plt.hist(data)
plt.show()

輸出結果:
111

plt.hist(data, bins=20)
plt.show()

輸出結果:
222

plt.hist(data, range=(4,5), bins=20)
plt.show()

輸出結果:
333

跟我們中學時期畫的直方圖一樣,都需要定若干個小區間,

  • plt.hist() 函數中的bins參數值就是這些小區間的個數,默認是10。
  • range=(4,5) 的意思就是選取橫座標軸4到5的部分顯示。

也可以爲y座標軸設置範圍:

plt.hist(data, range=(4,5), bins=20)

#定義y座標軸範圍爲0到50
plt.ylim(0,50)

plt.show()

輸出結果如下:
444

六、盒圖

繼續使用上面的數據,代碼如下:

plt.boxplot(data)
plt.show()

輸出結果:
555

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章