繪圖神器-matplotlib入門

來源:互聯網
上載者:User

標籤:aml   bin   就是   bar   cross   imshow   seed   十分   cat   

這次,讓我們使用一個非常有名且十分有趣的玩意兒來完成今天的任務,沒錯它就是jupyter。

一、安裝jupyter

matplotlib入門之前,先安裝好jupyter。這裡只提供最為方便快捷的安裝方式:pip install jupyter

我這裡已經裝過了

啟動jupyter也十分簡單:jupyter notebook

執行命令後,自動啟動服務,並自動開啟瀏覽器,jupyter就長這樣

找到你想要的目錄,右上方new-->python3建立一個可以執行python3代碼的jupyter檔案

新檔案長這樣。雖說每個cell獨立,但是下一個cell還是可以引用上一個cell的變數

補充:jupyter下一些常用的快捷命令

ctrl+enter    執行當前cell
shift+enter    執行當前cell並跳到下一個cell
dd            刪除當前cell
a            向上建一個cell
b            向下建一個cell
esc+m/m        將當前cell切換為markdown模式
esc+y/y        將當前cell切換為code模式
esc+l/l        顯示/隱藏當前cell的行號
o            收合或開啟當前cell的output
shift        選中多個cell
shift+m        合并多個cell

 

二、matplotlib入門

什麼是matplotlib?

官方給出的解釋是:Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code.

Matplotlib是一個Python的2D繪圖庫它以各種硬拷貝格式和跨平台的互動式環境產生出版品質層級的圖形。只需要幾行代碼,你就可以產生繪圖,長條圖,功率譜,橫條圖,錯誤圖,散佈圖等。

0.安裝依賴庫:matplotlib、numpy(pip install *)

numpy是python的一種開源的數值計算擴充庫。這種工具可用來進行大型矩陣資料類型處理、向量處理,以及精密運算。

(小聲說一句,這倆貨是機器學習三劍客中的兩個)

牛刀小試:

可以看到,代碼雖然只有3行,但卻非常直觀的繪製出了一條線形圖。

data = np.arange(100, 200) :產生100-200之間的整數數組,它的值是[100,101...200]

plt.plot(data):將上述數組繪製出來,對應圖中y軸,而matplotlib本身預設給我們設定了[0,100]的x軸,使其一一對應

plt.show():將圖片展示出來

1.繪製線形圖
import matplotlib.pyplot as pltplt.plot([100, 200, 300], [300, 600, 900], ‘-r‘)plt.plot([100, 200, 300], [200, 400, 900], ‘:g‘)plt.plot([200, 300, 400], [800, 100, 600], ‘-y‘)plt.show()

plot接受的三個參數,第一個參數是數組,作為x軸的值;第二個參數也是數組,作為y軸的值;第三個參數則表明線形圖是屬性,圖的構成和顏色,如上一依次是:紅色直線、綠色點線、黃色直線。

2.繪製散佈圖
import matplotlib.pyplot as pltimport numpy as npN = 20plt.scatter(np.random.rand(N) * 100,           np.random.rand(N) *100,           c=‘r‘, s=100, alpha=0.5)plt.scatter(np.random.rand(N) * 100,           np.random.rand(N) *100,           c=‘y‘, s=200, alpha=0.8)plt.scatter(np.random.rand(N) * 100,           np.random.rand(N) *100,           c=‘b‘, s=300, alpha=0.5)plt.show()

這幅圖包含了三組資料,每組資料都包含了20個隨機座標的位置。參數c表示點的顏色,s是點的大小,alpha是透明度

 scatter繪製散佈圖詳細文檔,參考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter

3.餅狀圖
import matplotlib.pyplot as pltimport numpy as nplabels = [‘suger‘, ‘popo‘, ‘python‘, ‘java‘, ‘ruby‘, ‘c#‘]data = np.random.rand(6) * 100plt.pie(data, labels=labels, autopct=‘%1.1f%%‘)plt.axis(‘equal‘)plt.legend()plt.show()

data是一組包含6個資料的隨機數值;圖中的標籤通過labels來指定;autopct指定了數值的精度格式;plt.axis(‘equal‘)設定了座標軸大小一致;plt.legend()指明要繪製圖。

 pie繪製餅狀圖詳細參考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html?highlight=pie#matplotlib.pyplot.pie

4.橫條圖
import matplotlib.pyplot as pltimport numpy as npN = 7x = np.arange(N)data = np.random.randint(low=0, high=100, size=N)colors = np.random.rand(N * 3).reshape(N, -1)labels = [‘Mon‘, ‘Tue‘, ‘Wed‘, ‘Thu‘, ‘Fri‘, ‘Sat‘, ‘Sun‘]plt.title(‘Weekday Data‘)plt.bar(x, data, alpha=0.8, color=colors, tick_label=labels)plt.show()

# 此圖展示了一組包含7個隨機數值的結果,每個數值是[0, 100]的隨機數
# 它們的顏色也是通過隨機數產生的。np.random.rand(N * 3).reshape(N, -1)表示先產生21(N x 3)個隨機數,然後將它們組裝成7行,那麼每行就是三個數,這對應了顏色的三個組成部分
# title指定了圖形的標題,labels指定了標籤,alpha是透明度

 bar繪製橫條圖官方文檔:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html?highlight=bar#matplotlib.pyplot.bar

5.長條圖
import matplotlib.pyplot as pltimport numpy as npdata = [np.random.randint(0, n, n) for n in [3000, 4000, 5000]]labels = [‘3k‘, ‘4k‘, ‘5k‘]bins = [0, 100, 500, 1000, 2000, 3000, 4000, 5000]plt.hist(data, bins=bins, label=labels)plt.legend()plt.show()

# [np.random.randint(0, n, n) for n in [3000, 4000, 5000]]產生了包含3個數組的數組:第一個數組包含了3000個隨機數,這些隨機數的範圍是 [0, 3000);第二個數組包含了4000個隨機數,這些隨機數的範圍是 [0, 4000);第三個數組包含了5000個隨機數,這些隨機數的範圍是 [0, 5000)

# bins設定長條圖的邊界。[0, 100, 500, 1000, 2000, 3000, 4000, 5000]一共設定了7個邊界,如:第一個邊界是[0,100),則有一個據點,符合邊界範圍的圖片將會在其中繪製

# 三組資料都有3000以下的資料,圖中3000以下的據點也都有資料,[3000,4000)據點沒有了3k的資料,而[4000,5000)據點則只剩下5k的資料了

hist繪製長條圖的更多用法:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html?highlight=hist#matplotlib.pyplot.hist

 

以上,目前我們已經學會了繪製簡單的線形圖、散佈圖、餅狀圖、橫條圖和長條圖,顯然這隻是皮毛,真正讓人歎為觀止的圖,盡在matplotlib gallery。

這裡摘取一個樣本:

import numpy as npimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecw = 3Y, X = np.mgrid[-w:w:100j, -w:w:100j]U = -1 - X**2 + YV = 1 + X - Y**2speed = np.sqrt(U*U + V*V)fig = plt.figure(figsize=(7, 9))gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])#  Varying density along a streamlineax0 = fig.add_subplot(gs[0, 0])ax0.streamplot(X, Y, U, V, density=[0.5, 1])ax0.set_title(‘Varying Density‘)# Varying color along a streamlineax1 = fig.add_subplot(gs[0, 1])strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=‘autumn‘)fig.colorbar(strm.lines)ax1.set_title(‘Varying Color‘)#  Varying line width along a streamlineax2 = fig.add_subplot(gs[1, 0])lw = 5*speed / speed.max()ax2.streamplot(X, Y, U, V, density=0.6, color=‘k‘, linewidth=lw)ax2.set_title(‘Varying Line Width‘)# Controlling the starting points of the streamlinesseed_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1,  0, 1, 2, 2]])ax3 = fig.add_subplot(gs[1, 1])strm = ax3.streamplot(X, Y, U, V, color=U, linewidth=2,                     cmap=‘autumn‘, start_points=seed_points.T)fig.colorbar(strm.lines)ax3.set_title(‘Controlling Starting Points‘)# Displaying the starting points with blue symbols.ax3.plot(seed_points[0], seed_points[1], ‘bo‘)ax3.axis((-w, w, -w, w))# Create a maskmask = np.zeros(U.shape, dtype=bool)mask[40:60, 40:60] = TrueU[:20, :20] = np.nanU = np.ma.array(U, mask=mask)ax4 = fig.add_subplot(gs[2:, :])ax4.streamplot(X, Y, U, V, color=‘r‘)ax4.set_title(‘Streamplot with Masking‘)ax4.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5,          interpolation=‘nearest‘, cmap=‘gray‘, aspect=‘auto‘)ax4.set_aspect(‘equal‘)plt.tight_layout()plt.show()

 

 

繪圖神器-matplotlib入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.