1. 程式人生 > >《機器學習實踐》2.2.2分析數據:使用matplotlib創建散點圖

《機器學習實踐》2.2.2分析數據:使用matplotlib創建散點圖

使用 其中 rate div space sca literal ax1 鏈接

#輸出散點圖
def f():
    datingDataMat,datingLabels = file2matrix("datingTestSet3.txt")

    fig = plt.figure()
    # ax = fig.add_subplot(199,projection=‘polar‘)
    # ax = fig.add_subplot(111,projection=‘hammer‘)
    # ax = fig.add_subplot(111,projection=‘lambert‘)
    # ax = fig.add_subplot(111,projection=‘mollweide‘)
# ax = fig.add_subplot(111,projection=‘aitoff‘) # ax = fig.add_subplot(111,projection=‘rectilinear‘) # ax = fig.add_subplot(111,projection=‘rectilinear‘) #此處的add_subplot參數的意思是把畫布分為3行4列,畫在從左到右從上到下的第2個格裏 ax = fig.add_subplot(3,4,2) #fig.add_subplot(342)也可以,但是這樣無法表示兩位數
ax.scatter(datingDataMat[:,
1],datingDataMat[:,2]) # ax1 = fig.add_subplot(221) # ax1.plot(datingDataMat[:,1],datingDataMat[:,2]) plt.show()
其中fig.add_subplot(3,4,2)的效果圖如下(紅框是我加的):

技術分享圖片
所以fig.add_subplot(3,4,12)的效果就是:
 技術分享圖片

所以,第三個參數不能超過前兩個的乘積,如果用fig.add_subplot(a,b,c)來表示的話,ab>=c,否則會報錯。

對於fig.add_subplot(3,4,12)這個函數,官方網站的解釋似乎有點問題,鏈接https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html?highlight=add_subplot#matplotlib.figure.Figure.add_subplot

查詢add_subplot(*args, **kwargs),得到如下解釋:

*args

Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are I, J, and K, the subplot is the Ith plot on a grid with J rows and K columns.

意思是,三個參數分別為I, J, K,表示J行K列,那I是什麽?沒有提及。

倒是下面的See also所指向的matplotlib.pyplot.subplot給出了正確的解釋。

matplotlib.pyplot.subplot

subplot(nrows, ncols, index, **kwargs)
 In the current figure, create and return an Axes, at position index of a (virtual) grid of nrows by ncols axes. Indexes go from 1 to nrows *ncols, incrementing in row-major order.

If nrows, ncols and index are all less than 10, they can also be given as a single, concatenated, three-digit number.

For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right corner of the current figure, occupying half of the figure height and a third of the figure width.

《機器學習實踐》2.2.2分析數據:使用matplotlib創建散點圖