1. 程式人生 > >【AI_常用Python庫】Matplotlib庫

【AI_常用Python庫】Matplotlib庫

這一篇博文是【 AI學習路線圖】系列文章的其中一篇,點選檢視目錄:AI學習完整路線圖

1、 介紹

matplolib是python裡最常用的繪相簿,提供了一整套十分適合互動式繪圖的命令API,比較方便地將其嵌入到GUI應用程式中。
matplolib中有兩個概念:Figure(面板)、Subplot(子圖)。
matplolib中所有的影象都是位於figure物件中的,一個影象只能有一個figure物件。
一個figure物件下可以建立多個subplot物件(即axas)用於繪製圖像。

2、 Figure和Subplot

import matplotlib.pyplot as
plt import numpy as np # 建立figure物件,8*6的大小(一般不設定大小),8是80% # 設定大小的目的是防止視窗太小 fig = plt.figure(figsize=(8, 6)) # —————————————————————————————————— # | | | # | | | # | 1 | 2 | # | | |
# | | | # ———————————————————————————————————— # | | | # | | | # | 3 | 4 | # | | | # | | | # ————————————————————————————————————
# 將面板分為2*2大小,新增標號為1的塊 ax1 = fig.add_subplot(2, 2, 1) # 將面板分為2*2大小,新增標號為2的塊 ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) # 1、繪製曲線,在當前axes上,目前是3上 ###### randn是正態分佈找隨機數 ###### cumsum累加和 plt.plot(np.random.randn(50).cumsum(), 'k--') # 2、繪製柱狀圖 ##### ax1.hist(np.random.randn(300), bins=20, color='k', alpha=0.3) # 3、繪製散點圖 #### ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30)) plt.show() 輸出: ``` ![輸出影象](http://upload-images.jianshu.io/upload_images/8658527-b9dc27155cddc376.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 畫線圖: ```python import matplotlib.pyplot as plt import numpy as np <div class="se-preview-section-delimiter"></div> # X軸的取值 x = np.arange(-5, 5) <div class="se-preview-section-delimiter"></div> # Y軸取值,是-5到5的siny = np.sin(np.arange(-5, 5)) <div class="se-preview-section-delimiter"></div> # 設定座標範圍 plt.axis([-5, 5, -5, 5]) <div class="se-preview-section-delimiter"></div> # 設定座標點,繪畫出線圖 plt.plot(x, y) <div class="se-preview-section-delimiter"></div> # 設定顯示一個文字 plt.text(-3, -3, '$y=sin(x)$', fontsize=20, bbox={'facecolor': 'yellow', 'alpha': 0.2}) plt.show() <div class="se-preview-section-delimiter"></div>

輸出的線圖

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, color='y')
plt.plot(x, y2, color='b')
plt.show()

輸出的影象