1. 程式人生 > >python繪圖matplotlib繪相簿入門

python繪圖matplotlib繪相簿入門

簡介:matplotlib 是Python最著名的繪相簿,它提供了一整套和matlab相似的命令API,十分適合互動式地行製圖。而且也可以方便地將它作為繪

圖控制元件,嵌入GUI應用程式中。

在Python中使用matplotlib.pyplot快速繪圖

下面是matplotlib庫所給的介紹

"""
This is an object-oriented plotting library.
 這是面向物件的繪相簿
A procedural interface is provided by the companion pyplot module,(程式介面直接import matplotlib.pyplot as plt 就可以了,或者使用ipython)
which may be imported directly, e.g.::

    import matplotlib.pyplot as plt

or using ipython::

    ipython

at your terminal, followed by::

    In [1]: %matplotlib
    In [2]: import matplotlib.pyplot as plt

at the ipython shell prompt.

For the most part, direct use of the object-oriented library is
encouraged when programming; pyplot is primarily for working
interactively.  The
exceptions are the pyplot commands :func:`~matplotlib.pyplot.figure`,
:func:`~matplotlib.pyplot.subplot`,
:func:`~matplotlib.pyplot.subplots`, and
:func:`~pyplot.savefig`, which can greatly simplify scripting.

Modules include: (matplotlib模組裡面有axes,figure,artist,lines,........)

    :mod:`matplotlib.axes`
        defines the :class:`~matplotlib.axes.Axes` class.  Most pylab
        commands are wrappers for :class:`~matplotlib.axes.Axes`
        methods.  The axes module is the highest level of OO access to
        the library.

    :mod:`matplotlib.figure`
        defines the :class:`~matplotlib.figure.Figure` class.

    :mod:`matplotlib.artist`
        defines the :class:`~matplotlib.artist.Artist` base class for
        all classes that draw things.

    :mod:`matplotlib.lines`
        defines the :class:`~matplotlib.lines.Line2D` class for
        drawing lines and markers

    :mod:`matplotlib.patches`
        defines classes for drawing polygons

    :mod:`matplotlib.text`
        defines the :class:`~matplotlib.text.Text`,
        :class:`~matplotlib.text.TextWithDash`, and
        :class:`~matplotlib.text.Annotate` classes

    :mod:`matplotlib.image`
        defines the :class:`~matplotlib.image.AxesImage` and
        :class:`~matplotlib.image.FigureImage` classes

    :mod:`matplotlib.collections`
        classes for efficient drawing of groups of lines or polygons

    :mod:`matplotlib.colors`
        classes for interpreting color specifications and for making
        colormaps

    :mod:`matplotlib.cm`
        colormaps and the :class:`~matplotlib.image.ScalarMappable`
        mixin class for providing color mapping functionality to other
        classes

    :mod:`matplotlib.ticker`
        classes for calculating tick mark locations and for formatting
        tick labels

    :mod:`matplotlib.backends`
        a subpackage with modules for various gui libraries and output
        formats

The base matplotlib namespace includes:

    :data:`~matplotlib.rcParams`
        a global dictionary of default configuration settings.  It is
        initialized by code which may be overridded by a matplotlibrc
        file.

    :func:`~matplotlib.rc`
        a function for setting groups of rcParams values

    :func:`~matplotlib.use`
        a function for setting the matplotlib backend.  If used, this
        function must be called immediately after importing matplotlib
        for the first time.  In particular, it must be called
        **before** importing pylab (if pylab is imported).

matplotlib was initially written by John D. Hunter (1968-2012) and is now
developed and maintained by a host of others.

Occasionally the internal documentation (python docstrings) will refer
to MATLAB®, a registered trademark of The MathWorks, Inc.

"""
閱讀後,我們明白matplotlib實際上是一套面向物件的繪相簿,它所繪製的圖表中的每個繪圖元素,例如線條Line2D、文字Text、刻度等在記憶體中都有一個物件與之對應。

我們只需要呼叫pyplot模組所提供的函式就可以實現快速繪圖以及設定圖表的各種細節。

def sca(ax):
    """
    Set the current Axes instance to *ax*.

    The current Figure is updated to the parent of *ax*.
    """
    managers = _pylab_helpers.Gcf.get_all_fig_managers()
    for m in managers:
        if ax in m.canvas.figure.axes:
            _pylab_helpers.Gcf.set_active(m)
            m.canvas.figure.sca(ax)
            return
    raise ValueError("Axes instance argument was not found in a figure.")
def gcf():
    "Get a reference to the current figure."

    figManager = _pylab_helpers.Gcf.get_active()
    if figManager is not None:
        return figManager.canvas.figure
    else:
        return figure()
為了將面向物件的繪相簿包裝成只使用函式的呼叫介面,pyplot模組的內部儲存了當前圖表以及當前子圖等資訊。當前的圖表和子圖可以使用plt.gcf()和plt.gca()獲得,分別表示"Get Current Figure"和"Get Current Axes"。在pyplot模組中,許多函式都是對當前的Figure或Axes物件進行處理,比如說:

plt.plot()實際上會通過plt.gca()獲得當前的Axes物件ax,然後再呼叫ax.plot()方法實現真正的繪圖。


繪製多子圖(快速繪圖)

Matplotlib 裡的常用類的包含關係為 Figure -> Axes -> (Line2D, Text, etc.)一個Figure物件可以包含多個子圖(Axes),在matplotlib中用Axes物件表示一個繪圖區域,可以理解為子圖。
可以使用subplot()快速繪製包含多個子圖的圖表,它的呼叫形式如下:
subplot(numRows, numCols, plotNum)
subplot將整個繪圖區域等分為numRows行* numCols列個子區域,然後plotNum(1<=plotNum<=4且plotNum必須為正整數)按照從左到右,從上到下的順序對每個子區域進行編號,左上的子區域的編號為1。如果numRows,numCols和plotNum這三個數都小於10的話,可以把它們縮寫為一個整數,例如subplot(323)和subplot(3,2,3)是相同的,其中最後一位的3表示在第三象限畫圖的。subplot在plotNum指定的區域中建立一個軸物件。如果新建立的軸和之前建立的軸重疊的話,之前的軸將被刪除。


'''  為了方便快速繪圖matplotlib通過pyplot模組提供了一套和MATLAB類似的繪圖API,
將眾多繪圖物件所構成的複雜結構隱藏在這套API內部。
我們只需要呼叫pyplot模組所提供的函式就可以實現快速繪圖以及設定圖表的各種細節  '''
''' plt.plot()實際上會通過plt.gca()獲得當前的Axes物件ax,然後再呼叫ax.plot()方法實現真正的繪圖。 '''
def learn2():
    plt.figure(1)  # 建立圖表1
    plt.figure(2)  # 建立圖表2
    ax1 = plt.subplot(211)  # 在圖表2中建立子圖1
    ax2 = plt.subplot(212)  # 在圖表2中建立子圖2
    x = np.linspace(0, 3, 100)
    for i in xrange(5):
        plt.figure(1)  # 選擇圖表1
        # plt.plot(x, np.exp(i * x / 3), 'o')
        plt.sca(ax1) # 將子圖1放進for釐面的plt中
        plt.plot(x, np.sin(i * x))
        plt.sca(ax2)
        plt.plot(x, np.cos(i * x))
    plt.show()

參考來自:http://blog.csdn.net/ywjun0919/article/details/8692018

相關推薦

python繪圖matplotlib相簿入門

簡介:matplotlib 是Python最著名的繪相簿,它提供了一整套和matlab相似的命令API,十分適合互動式地行製圖。而且也可以方便地將它作為繪圖控制元件,嵌入GUI應用程式中。 在Python中使用matplotlib.pyplot快速繪圖 下面是matplot

Python圖表繪製:matplotlib相簿入門

matplotlib 是python最著名的繪相簿,它提供了一整套和matlab相似的命令API,十分適合互動式地行製圖。而且也可以方便地將它作為繪圖控制元件,嵌入GUI應用程式中。 它的文件相當完備,並且Gallery頁面中有上百幅縮圖,開啟之後都有源程式。因此如果你需要繪製某種型別的圖,只需要在這個頁面

Pythonmatplotlib制折線圖

圖片 add 但我 修復 put inline Coding 嘗試 ram 一、繪制簡單的折線圖 import matplotlib.pyplot as plt squares=[1,4,9,16,25] plt.plot(squares) plt.show() 我

Python繪圖matplotlib

mco 設置 處理 mes 接口 led 模塊 stack sts 轉自http://blog.csdn.net/ywjun0919/article/details/8692018 Python圖表繪制:matplotlib繪圖庫入門 matplotlib 是pytho

pythonmatplotlib庫畫圖入門

    什麼是matplotlib呢?其實matplotlib是python的一個包(庫)。在您的計算機裡安裝anaconda這個軟體,就可以直接使用這個包了。另外anaconda中集成了很多的python包,自帶我們常用的Jupyter Notebook,是

Python繪圖Matplotlib教程(詳細版)前半部分

一直將matplotlib當做一個工具來用,因為沒有了解到它的特性,所以一直學得不繫統,導致用到的時候經常要查官方文件。這裡翻譯一個官方推薦的matplotlib的介紹文件。 猛戳進入原文連結 文件中包含的內容: 簡介 簡單的例子 matplotlib元

matplotlib 相簿的簡單用法

首先在ipyhon啟動的時候一定要加上–pylab,否則,無法進行繪圖操作,而在spyder環境下,開啟一個ipython 的console貌似預設是不會加上這個選項的,所以用spyder環境,無法正常繪圖。現在直接在cmd下輸入ipython –pylab開始

Pythonmatplotlib制散點圖

代碼 使用 有用 使用方式 配置 說明 不同 mat auto 與線型圖類似的是,散點圖也是一個個點集構成的。但不同之處在於,散點圖的各點之間不會按照前後關系以線條連接起來。 用plt.plot畫散點圖 奇怪,代碼和前面的例子差

python 相簿 Matplotlib

matplotlib官方文件 使用Matplotlib,能夠輕易生成各種影象,例如:直方圖、波譜圖、條形圖、散點圖等。 入門程式碼例項 import matplotlib.pyplot as plt import numpy as np

Python的機器學習庫scikit-learn、相簿Matplotlib的安裝

在windows環境下安裝scipy和sklearn是一件比較麻煩的事情。由於sklearn依賴於numpy和scipy,所以安裝sklearn之前需要先安裝numpy和scipy庫,然而使用pip安裝安裝時,pip install numpy 可以安裝成功,但是使用命令p

Python開發【模塊】:matplotlib 制折線圖

ins inux cnblogs linux linu free logs strong use matplotlib 1、安裝matplotlib ① linux系統 # 安裝matplotlib模塊 $ sudo apt-get install python-ma

python繪圖入門

otl 繪制圖形 for __init__ axis list htm matplot scatter python繪圖入門 學習了:https://zhuanlan.zhihu.com/p/34200452 API:https://matplotlib.org/api/p

python讀csv格式文檔並用matplotlib制圖表

IT ima ont 技術 pen highlight png src 同時 import csv from matplotlib import pyplot as plt from datetime import datetime fileName = ‘sitk

機器學習入門之使用numpy和matplotlib制圖形

作用 應該 方式 9.png 5.1 環境 就是 清華大學 圖1   機器學習當中能深入淺出的方法第一步就是先學會用numpy了。numpy是一個第三方的開源python庫,他提供了許多科學的數值計算工具,尤其是大型矩陣計算,但使用配置非常簡單,結合matplotlib能夠

python使用matplotlib:subplot制多個子圖

很好 分享 encoding matplot term 繪圖 nco 一個 enume 1 問題描述 matploglib 能夠繪制出精美的圖表, 有些時候, 我們希望把一組圖放在一起進行比較, 有沒有什麽好的方法呢? matplotlib 中提供的 subplot 可以

python 使用matplotlib,pylab進行python繪圖

既然繪圖要用matplotlib的包,並且我們也已經安裝了,那麼首先肯定是要引入這個包了: import matplotlib.pyplot as plt    當然也可以替換為引入pylab(是matplotlib的一個子包,非常適合於進行互動式繪圖,本文將以

Python繪圖之——matplotlib顏色與線條

常用顏色: 八種內建預設顏色縮寫 b: blue   g: green   r: red   c: cyan   m: magenta   y: yellow   k: black

pythonmatplotlib.pyplot包基本繪圖方法詳解

一般情況下,我們使用以下語句引入該包: import matplotlib.pyplot as plt 全域性中文字型設定: pyplot包並不預設支援中文顯示,需要rcParams修改字型來實現。 import matplotlib.pyplot as plt from pyl

Python三維繪圖--Matplotlib

Python三維繪圖 在遇到三維資料時,三維影象能給我們對資料帶來更加深入地理解。python的matplotlib庫就包含了豐富的三維繪圖工具。 1.建立三維座標軸物件Axes3D 建立Axes3

Python學習筆記2】turtle庫相簿使用

5.in[‘C’,’c’]保留字,二元關係操作,符合右側即為真, 6.print(“這裡輸入文字:%.2fF”%f)表示二位小數的浮點數,%f表示輸出的是f的值。 7.迴圈 for i in range (10):                      執行 8.