tft每日頭條

 > 圖文

 > matplotlib畫圖方式

matplotlib畫圖方式

圖文 更新时间:2024-06-24 03:51:57

前言

本篇開始學習Matplotlib的常規用法,以及最佳實踐幫助你掌握Matplotlib庫。

一個簡單的例子

創建一個圖表(Figure),裡面包含一個坐标軸(Axes)

# Create a figure containing a single axes. fig, ax = plt.subplots() # Plot some data on the axes ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) plt.show()

Figure(相當于一個繪制窗口、或者是繪制組件),每個Figure包含一個Axes,Axes可以繪制x-y-z坐标軸的圖形。以上調用創建一個二維的坐标圖

matplotlib畫圖方式(Matplotlib基本用法上繪制)1

坐标軸

圖表組件

有些名詞翻譯成中文反而不好理解,所以後續對于重點名詞不翻譯,以下四個非常重要

(1) Figure

Figure保存所有的Axes記錄,Axes由一系列的Artist組成。最簡單的創建Figure的方式

fig = plt.figure() # an empty figure with no Axes fig, ax = plt.subplots() # a figure with a single Axes fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of AxesAxes

(2) Axes

Axes是附着于Figure之上,通常包含兩個Axis對象,可以對Axes上的數據進行拉伸操作。Axes可以通過set_title()函數改變名字。

(2) Axis(軸)

通過Locator決定點的位置,通過Formatter生成點的标簽。

(4) Artist

所有Figure上可見的東西都是Artist(包括Figure, Axes, Axis, Text, Line2D, Patch)等。所有的Artist都是通過canvas進行繪制的,絕大部分的Artists都依附于Axes。

輸入數據的種類

繪制函數都需要numpy.array或者numpy.ma.masked_array數組作為輸入,或者可以傳遞到numpy.asarray的對象。一些和數組相似的類,比如pandas, dumpy.matrix是不能傳遞到繪制函數上的,它們都需要轉化為numpy.array對象。

b = np.matrix([[1, 2], [3, 4]]) b_asarray = np.asarray(b)

輸出

[[1 2] [3 4]]

繪制函數也可以解析類似dict,numpy.recarray, pandas.DataFrame等可尋址的對象。

np.random.seed(19680801) # seed the random number generator. data = {'a': np.arange(50), 'c': np.random.randint(0, 50, 50), 'd': np.random.randn(50)} data['b'] = data['a'] 10 * np.random.randn(50) data['d'] = np.abs(data['d']) * 100 fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') ax.scatter(x='a', y='b', c='c', s='d', data=data) ax.set_xlabel('entry a') ax.set_ylabel('entry b');

scatter()函數中x和y表示坐标位置,c表示坐标點的顔色,s表示坐标點的大小,data表述傳遞進來的數據。

matplotlib畫圖方式(Matplotlib基本用法上繪制)2

傳遞數據

編碼風格

有兩種使用Matplotlib繪制的方式:

  1. 創建Figure和Axes對象,通過對象調用相關方法;
  2. 依靠pyplot自動創建和管理Figure和Axes,使用pyplot函數進行繪制

使用面向對象的方式

x = np.linspace(0, 2, 100) # Sample data. # Note that even in the OO-style, we use `.pyplot.figure` to create the Figure. fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') ax.plot(x, x, label='linear') # Plot some data on the axes. ax.plot(x, x**2, label='quadratic') # Plot more data on the axes... ax.plot(x, x**3, label='cubic') # ... and some more. ax.set_xlabel('x label') # Add an x-label to the axes. ax.set_ylabel('y label') # Add a y-label to the axes. ax.set_title("Simple Plot") # Add a title to the axes. ax.legend() # Add a legend. plt.show()

繪制三條線條

matplotlib畫圖方式(Matplotlib基本用法上繪制)3

編碼風格

使用pyplot方式繪制

x = np.linspace(0, 2, 100) # Sample data. plt.figure(figsize=(5, 2.7), layout='constrained') plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes. plt.plot(x, x**2, label='quadratic') # etc. plt.plot(x, x**3, label='cubic') plt.xlabel('x label') plt.ylabel('y label') plt.title("Simple Plot") plt.legend() plt.show()

得到的結果和面向對象一樣的,還有第三種繪制方式,後續會介紹。Matplotlib的示例中面向對象的方式和pyplot的方式都會使用。通常來說建議使用面向對象的方式,但是pyplot的方式可以更快遞完成交互工作。

如果有代碼重複的地方,可以編寫幫助函數,比如重複繪制一些點:

def my_plotter(ax, data1, data2, param_dict): """ A helper function to make a graph. """ out = ax.plot(data1, data2, **param_dict) return out

傳遞不同的數據調用幫助函數繪制

data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data sets fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7)) my_plotter(ax1, data1, data2, {'marker': 'x'}) my_plotter(ax2, data3, data4, {'marker': 'o'}) plt.show()

marker是點的标記形式

matplotlib畫圖方式(Matplotlib基本用法上繪制)4

幫助函數

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部
祝福詞

相关圖文资讯推荐

热门圖文资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved