<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # 1.4 Matplotlib:繪圖 ## 1.4.1 簡介 [Matplotlib](http://matplotlib.org/) 可能是Python惟一一個最廣泛使用的二維圖包。它同時提供了從Python中可視化數據非常的快速方式以及多種格式的出版質量圖片。我們將在交互模式下研究Matplotlib,包含大多數的常用案例。 ### 1.4.1.1 IPython和pylab模式 [IPython](http://ipython.org/)是強化版交互Python shell,有許多有趣的功能,包括:輸入輸出的命名、訪問shell命令改進錯誤排除等。它位于Python中的科學計算工作流的核心,要讓它與Matplotlib的結合使用: 用命令行參數 `-pylab`(`--pylab` 從IPython0.12開始)啟動IPython,獲得帶有Matlab/Mathematica類似功能的交互Matplotlib session。 ### 1.4.1.2 pylab _pylab_提供了matplotlib面向對象的繪圖庫的程序接口。它的模型與Matlab?非常相近。因此,pylab中的絕大多數繪圖命令Matlab?都有帶有相似函數的類似實現。重要的命令會以交互例子來解釋。 ## 1.4.2 簡單繪圖 在這個部分,我們將在同一個圖像中繪制cosine和sine函數。從默認設置開始,我們將不斷豐富圖片,讓它看起來更漂亮。 第一步獲得sine和cosine函數的數據: In?[2]: ``` import numpy as np X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) ``` `X`現在是Numpy數組,范圍是`-π`到`+π`之間(包含)的256個值。C是cosine(256個值),而S是sine(256個值) 要運行例子,你可以在IPython的交互session中輸入這些命令: ``` ipython --pylab ``` 這會將我們帶到IPython提示符: ``` IPython 2.3.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. Using matplotlib backend: MacOSX ``` 你可以下載每個示例,然后用平常的Python運行,但是,你將沒法動態的數據操作: ``` python exercice_1.py ``` 通過點擊對應的圖片,你可以獲得每一步的源碼。 ### 1.4.2.1 用默認設置繪圖 **提示**:文檔 * [plot教程](http://matplotlib.sourceforge.net/users/pyplot_tutorial.html) * [plot()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot) Matplotlib有一組默認設置,允許自定義所有的屬性。你幾乎可以控制在matplotlib中的所有屬性:圖片大小和dpi、線長度、顏色和樣式、坐標軸、坐標軸和網格屬性、文本和字體屬性等等。 ``` import pylab as pl import numpy as np X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) pl.plot(X, C) pl.plot(X, S) pl.show() ``` [![plot_exercice_1_1.png](http://scipy-lectures.github.io/_images/plot_exercice_1_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_1.html) ### 1.4.2.2 默認值示例 **提示**:文檔 * [自定義matplotlib](http://matplotlib.sourceforge.net/users/customizing.html) 在下面的腳本中,我們標示(備注)了影響繪圖外觀的所有圖片設置。 這些設置被顯式的設置為默認值,但是現在你可以交互的實驗這些值以便驗證他們的效果(看一下下面的[線屬性](http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#line-properties)和[線樣式](http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#line-styles))。 ``` import pylab as pl import numpy as np # 創建一個大小為 8X6 英寸,每英寸80個點的圖片 pl.figure(figsize=(8, 6), dpi=80) # 從1X1的網格創建一個子圖片 pl.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) # 用寬度為1(像素)的藍色連續直線繪制cosine pl.plot(X, C, color="blue", linewidth=1.0, linestyle="-") # 用寬度為1(像素)的綠色連續直線繪制sine pl.plot(X, S, color="green", linewidth=1.0, linestyle="-") # 設置x軸的極值 pl.xlim(-4.0, 4.0) # 設置x軸的刻度值 pl.xticks(np.linspace(-4, 4, 9, endpoint=True)) # 設置y軸的極值 pl.ylim(-1.0, 1.0) # 設置y軸的刻度值 pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) # 用72dpi保存圖片 # savefig("exercice_2.png", dpi=72) # 在屏幕上顯示結果 pl.show() ``` [![plot_exercice_2_1.png](http://scipy-lectures.github.io/_images/plot_exercice_2_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_2.html) ### 1.4.2.3 改變顏色和線寬度 **提示**:文檔 * [控制線屬性](http://matplotlib.sourceforge.net/users/pyplot_tutorial.html#controlling-line-properties) * [線API](http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.Line2D) 首先,我們想要cosine是藍色,sine是紅色,兩者都是稍稍粗一點的線。我們也改變了一點圖片的大小,讓它更加水平。 ``` pl.figure(figsize=(10, 6), dpi=80) pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") ``` [![plot_exercice_3_1.png](http://scipy-lectures.github.io/_images/plot_exercice_3_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_3.html) ### 1.4.2.4 設置極值 **提示**:文檔 * [xlim()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xlim) * [ylim()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ylim) 當前的圖片的極值限制太擁擠了,我們希望留一點空間以便清晰的看到所有的數據點。 ``` pl.xlim(X.min() * 1.1, X.max() * 1.1) pl.ylim(C.min() * 1.1, C.max() * 1.1) ``` [![plot_exercice_4_1.png](http://scipy-lectures.github.io/_images/plot_exercice_4_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_4.html) ### 1.4.2.5 設置坐標軸刻度值 **提示**:文檔 * [xticks()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks) * [yticks()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.yticks) * [刻度容器](http://matplotlib.sourceforge.net/users/artists.html#axis-container) * [刻度位置和格式](http://matplotlib.sourceforge.net/api/ticker_api.html) 現在的刻度不太理想,因為他們沒有顯示對于sine和cosine有意義的值(+/-π,+/-π/2)。我們將改變這些刻度,讓他們只顯示這些值。 ``` pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) pl.yticks([-1, 0, +1]) ``` [![plot_exercice_5_1.png](http://scipy-lectures.github.io/_images/plot_exercice_5_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_5.html) ### 1.4.2.6 設置刻度標簽 **提示**:文檔 * [操作文本](http://matplotlib.sourceforge.net/users/index_text.html) * [xticks()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks) * [yticks()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.yticks) * [set_xticklabels()](http://matplotlib.sourceforge.net/api/axes_api.html?#matplotlib.axes.Axes.set_xticklabels) * [set_yticklabels()](http://matplotlib.sourceforge.net/api/axes_api.html?#matplotlib.axes.Axes.set_yticklabels) 刻度現在放在了正確的位置,但是標簽并不是顯而易見。我們能想到3.14是π,但是最好讓它更明確。 當我們設置了刻度值,我們也可以在第二個參數中列出對應的標簽。注意我們用latex以便更好的渲染標簽。 ``` pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) pl.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$']) ``` ### 1.4.2.7 移動脊柱 **提示**:文檔 * [脊柱](http://matplotlib.sourceforge.net/api/spines_api.html#matplotlib.spines) * [坐標軸容器](http://matplotlib.sourceforge.net/users/artists.html#axis-container) * [轉換教程](http://matplotlib.sourceforge.net/users/transforms_tutorial.html) 脊柱是連接坐標軸刻度標記的線,記錄了數據范圍的邊界。他們可以被放在任意的位置,到目前位置,他們被放在了坐標軸的四周。我們將改變他們,因為我們希望他們在中間。因為有四條(上下左右),我們通過設置顏色為None舍棄了頂部和右側,并且我們將把底部和左側的脊柱移動到數據空間坐標的零點。 ``` ax = pl.gca() # gca stands for 'get current axis' ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) ``` [![plot_exercice_7_1.png](http://scipy-lectures.github.io/_images/plot_exercice_7_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_7.html) ### 1.4.2.8 添加圖例 **提示**:文檔 * [圖例指南](http://matplotlib.sourceforge.net/users/legend_guide.html) * [legend()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.legend) * [圖例API](http://matplotlib.sourceforge.net/api/legend_api.html#matplotlib.legend.Legend) 讓我們在坐上角添加圖例。這只需要在plot命里中添加關鍵詞參數label(將被用于圖例框)。 ``` pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") pl.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") pl.legend(loc='upper left') ``` [![../../_images/plot_exercice_8_1.png](http://scipy-lectures.github.io/_images/plot_exercice_8_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_8.html) ### 1.4.2.9 標注一些點 **提示**:文檔 * [注釋坐標軸](http://matplotlib.sourceforge.net/users/annotations_guide.html) * [annotate()命令](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.annotate) 讓我們用annotate命令標注一些有趣的點。我們選取值2π/3,我們想要標注sine和cosine。首先我們在曲線上畫出了一個垂直的散點標記線。然后,我們將用annotate命令顯示帶有剪頭的文字。 ``` t = 2 * np.pi / 3 pl.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--") pl.scatter([t, ], [np.cos(t), ], 50, color='blue') pl.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) pl.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") pl.scatter([t, ],[np.sin(t), ], 50, color='red') pl.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) ``` [![plot_exercice_9_1.png](http://scipy-lectures.github.io/_images/plot_exercice_9_1.png)](http://scipy-lectures.github.io/intro/matplotlib/auto_examples/plot_exercice_9.html) ### 1.4.2.10 細節是魔鬼 **提示**:文檔 * [Artists](http://matplotlib.sourceforge.net/api/artist_api.html) * [BBox](http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.text.Text.set_bbox) 因為藍色和紅色的線,刻度標簽很難看到。我們可以讓他們更大一些,也可以調整他們的屬性以便他們被處理為半透明的白色背景。這樣我們就可以同時看到數據和標簽。 ``` for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(16) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) ``` [![plot_exercice_10_1.png](http://scipy-lectures.github.io/_images/plot_exercice_10_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_exercice_10.html) ## 1.4.3 圖形、子圖、軸和刻度 在matplotlib中“**圖形**”是用戶界面中的整個窗口。在這個圖形中可以有“**子圖**”。 到目前為止,我們已經使用圖形和創建數軸。這對于快速繪圖是非常方便的。使用圖形、子圖和軸我們可以控制顯示。盡管子圖將圖表放在標準的網格中,軸可以在圖形中放在任意位置。根據你的目的不同,二者都非常有用。我們也在沒有顯式的調用圖形和子圖時使用了他們。當我們調用plot時,matplotlib調用`gca()`來獲得當前的坐標軸,相應的調用`gcf()`獲得當前的圖形。如果沒有當前圖形,那么將調用`figure()`去創建一個,嚴格來說是創建一個`subplot(111)。讓我們來詳細看一下。 ### 1.4.3.1 圖形 圖形是在GUI中的窗口,標題是"Figure #"。圖形的標號從1開始,而不是常規的Python方式從0開始。這明顯是MATLAB-風格。這些參數決定圖形的外觀: | 參數 | 默認值 | 描述 | | --- | --- | --- | | num | 1 | 圖形編號 | | figsize | figure.figsize | 以英寸表示的圖形大小(寬、高) | | dpi | figure.dpi | 分辨率以每英寸點數表示 | | facecolor | figure.facecolor | 背景色 | | edgecolor | figure.edgecolor | 背景邊緣色 | | frameon | True | 是否繪制框架 | 默認值可以在資源文件中指明,并在絕大數時間使用。只有圖形數經常被改變。 與其他對象類似,你可以用setp或者set_something方法設置圖形屬性。 當你使用GUI工作時,你可以點擊右上的X關閉圖形。但是,你可以通過調用close用程序關閉圖形。根據參數關閉不同內容(1)當前圖形(沒有參數),(2)特定圖形(用圖形編號或圖形實例做參數),(3)所有圖形("all"作為參數)。 ``` pl.close(1) # Closes figure 1 ``` ### 1.4.3.2 子圖 用子圖你可以將圖片放置在標準方格中。你需要指定行列數和圖片數。 注意[gridspec](http://matplotlib.org/users/gridspec.html)命令相對更加高級。 [![plot_subplot-horizontal_1.png](http://scipy-lectures.github.io/_images/plot_subplot-horizontal_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_subplot-horizontal.html)[![plot_subplot-vertical_1.png](http://scipy-lectures.github.io/_images/plot_subplot-vertical_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_subplot-vertical.html)[![plot_subplot-grid_1.png](http://scipy-lectures.github.io/_images/plot_subplot-grid_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_subplot-grid.html)[![plot_gridspec_1.png](http://scipy-lectures.github.io/_images/plot_gridspec_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_gridspec.html) ### 1.4.3.3 軸 軸與子圖非常類似,不過允許圖形放在圖片的任意位置。因此,如果我們想要將一個小圖形放在一個更大圖形中,我們可以用軸。 [![plot_axes_1.png](http://scipy-lectures.github.io/_images/plot_axes_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_axes.html)[![plot_axes-2_1.png](http://scipy-lectures.github.io/_images/plot_axes-2_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_axes-2.html) ### 1.4.3.4 刻度 格式良好的刻度是準備好發布圖片的必要部分。Matplotlib提供了一個完全可控的刻度系統。有刻度位置來指定刻度該出現在哪,還有刻度格式來給出你想要的刻度外觀。主刻度和子刻度可以被獨立放置和整理格式。之前子刻度默認是不顯示的,即他們只有空列表,因為它是`NullLocator` (見下面)。 #### 1.4.3.4.1 刻度位置 刻度位置可以控制的位置。它的設置如下: ``` ax = pl.gca() ax.xaxis.set_major_locator(eval(locator)) ``` 不同的需求有多種位置: [![plot_ticks_1.png](http://scipy-lectures.github.io/_images/plot_ticks_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_ticks.html) 所有這些位置都可以從基礎類[matplotlib.ticker.Locator](http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.Locator)衍生出來。你可以從中衍生出你自己的位置。將日期處理為刻度特別困哪。因此,`matplotlib`提供了特殊的位置`matplotlib.dates`。 ## 1.4.4 其他類型的圖形:例子與練習 ### 1.4.4.1 常規圖形 **提示:**你可以使用[fill_between](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.fill_between)命令。 [![plot_plot_ex_1.png](http://scipy-lectures.github.io/_images/plot_plot_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_plot_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理填充區域: ``` n = 256 X = np.linspace(-np.pi, np.pi, n, endpoint=True) Y = np.sin(2 * X) pl.plot(X, Y + 1, color='blue', alpha=1.00) pl.plot(X, Y - 1, color='blue', alpha=1.00) ``` 點擊圖片查看答案。 ### 1.4.4.2 散點圖 **提示:**顏色根據角度進行分配 [![plot_scatter_ex_1.png](http://scipy-lectures.github.io/_images/plot_scatter_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_scatter_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理標記的大小顏色和透明度: ``` n = 1024 X = np.random.normal(0,1,n) Y = np.random.normal(0,1,n) pl.scatter(X,Y) ``` 點擊圖片查看答案。 ### 1.4.4.3 柱狀圖 **提示:**你需要小心文本對齊 [![plot_bar_ex_1.png](http://scipy-lectures.github.io/_images/plot_bar_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_bar_ex.html) 從下面的代碼開始,試著重新生成這個圖片,添加紅柱的標簽。 ``` n = 12 X = np.arange(n) Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) pl.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') pl.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') for x, y in zip(X, Y1): pl.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom') pl.ylim(-1.25, +1.25) ``` 點擊圖片查看答案。 ### 1.4.4.4 輪廓圖 **提示:**你需要是使用[clabel](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.clabel)命令。 [![plot_contour_ex_1.png](http://scipy-lectures.github.io/_images/plot_contour_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_contour_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理colormap (見下面的[Colormaps](http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#colormaps))。 ``` def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2) n = 256 x = np.linspace(-3, 3, n) y = np.linspace(-3, 3, n) X, Y = np.meshgrid(x, y) pl.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet') C = pl.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) ``` 點擊圖片查看答案。 ### 1.4.4.5 Imshow **提示:**你需要小心處理在imshow命令中的圖像_原點_并使用[colorbar](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.colorbar) [![plot_imshow_ex_1.png](http://scipy-lectures.github.io/_images/plot_imshow_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_imshow_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理colormap和圖像插入以及原點。 ``` def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) n = 10 x = np.linspace(-3, 3, 4 * n) y = np.linspace(-3, 3, 3 * n) X, Y = np.meshgrid(x, y) pl.imshow(f(X, Y)) ``` 點擊圖片查看答案。 ### 1.4.4.6 餅圖 **提示:**你需要調整Z。 [![plot_pie_ex_1.png](http://scipy-lectures.github.io/_images/plot_pie_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_pie_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理顏色和切片大小。 ``` Z = np.random.uniform(0, 1, 20) pl.pie(Z) ``` 點擊圖片查看答案。 ### 1.4.4.7 梯度圖 **提示:**你需要繪制兩次箭頭。 [![plot_quiver_ex_1.png](http://scipy-lectures.github.io/_images/plot_quiver_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_quiver_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理顏色和方向。 ``` n = 8 X, Y = np.mgrid[0:n, 0:n] pl.quiver(X, Y) ``` 點擊圖片查看答案。 ### 1.4.4.8 網格 [![plot_grid_ex_1.png](http://scipy-lectures.github.io/_images/plot_grid_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_grid_ex.html) 從下面的代碼開始,試著重新生成這個圖片,小心處理線的樣式。 ``` axes = pl.gca() axes.set_xlim(0, 4) axes.set_ylim(0, 3) axes.set_xticklabels([]) axes.set_yticklabels([]) ``` 點擊圖片查看答案。 ### 1.4.4.9 多圖 **提示:**你可以用不同的分割來使用多個子圖。 [![plot_multiplot_ex_1.png](http://scipy-lectures.github.io/_images/plot_multiplot_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_multiplot_ex.html) ``` pl.subplot(2, 2, 1) pl.subplot(2, 2, 3) pl.subplot(2, 2, 4) ``` 點擊圖片查看答案。 ### 1.4.4.10 極坐標系 **提示:**你只需要修改`axes`行。 [![plot_polar_ex_1.png](http://scipy-lectures.github.io/_images/plot_polar_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_polar_ex.html) 從下面的代碼開始,試著重新生成這個圖片。 ``` pl.axes([0, 0, 1, 1]) N = 20 theta = np.arange(0., 2 * np.pi, 2 * np.pi / N) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) bars = pl.bar(theta, radii, width=width, bottom=0.0) for r, bar in zip(radii, bars): bar.set_facecolor(cm.jet(r / 10.)) bar.set_alpha(0.5) ``` 點擊圖片查看答案。 ### 1.4.4.11 3D繪圖 **提示:**你需要使用[contourf](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.contourf) [![plot_plot3d_ex_1.png](http://scipy-lectures.github.io/_images/plot_plot3d_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_plot3d_ex.html) 從下面的代碼開始,試著重新生成這個圖片。 ``` from mpl_toolkits.mplot3d import Axes3D fig = pl.figure() ax = Axes3D(fig) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot') ``` 點擊圖片查看答案。 **更多請見**:[用Mayavi 3D繪圖](http://scipy-lectures.github.io/packages/3d_plotting/index.html#mayavi-label) ### 1.4.4.12 文本 **提示:**看一下[matplotlib標識](http://matplotlib.org/examples/api/logo2.html) [![plot_text_ex_1.png](http://scipy-lectures.github.io/_images/plot_text_ex_1.png)](http://scipy-lectures.github.io/intro/auto_examples/plot_text_ex.html) 試著從0開始做這個事情! 點擊圖片查看答案。 **快速閱讀** 如果你想要快速看一下Scipy講座以便了解生態系統,你可以直接跳到下一章:Scipy:高級科學計算。 本章的剩余部分對理解其他的介紹部分不是必須的。但是,請確保在稍后回來完成這個章節。 ## 1.4.5 這本教程之外 Matplotlib從大量的文檔以及用戶和開發者社區中收益匪淺。這里是一些有趣的鏈接: ### 1.4.5.1 教程 * [Pyplot教程](http://matplotlib.sourceforge.net/users/pyplot_tutorial.html) * 介紹 * 控制line屬性 * 處理多個圖形和坐標軸 * 處理文本 * [Image教程](http://matplotlib.sourceforge.net/users/image_tutorial.html) * 開始命令 * 從Numpy數組中導入圖像數據 * 將numpy數組繪制為圖像 * [Text教程](http://matplotlib.sourceforge.net/users/index_text.html) * Text介紹 * 基本text命令 * Text屬性和布局 * 寫數學表達式 * 用LaTeX渲染文本 * 文本注釋 * [Artist教程](http://matplotlib.org/users/artists.html) * 介紹 * 自定義你的對象 * 對象容器 * Figure容器 * Axes容器 * Axis容器 * 刻度容器 * [Path教程](http://matplotlib.sourceforge.net/users/path_tutorial.html) * 介紹 * Bézier例子 * 復合路徑 * [轉換教程](http://matplotlib.sourceforge.net/users/transforms_tutorial.html) * 介紹 * 數據坐標 * Axes坐標 * 混合轉換 * 用offset轉換來穿件一個陰影效果 * pipline轉換 ### 1.4.5.2 Matplotlib文檔 * [用戶手冊](http://matplotlib.sourceforge.net/users/index.html) * [常見問題](http://matplotlib.sourceforge.net/faq/index.html) * 安裝 * 使用 * 如何使用 * 故障排除 * 環境變量 * [屏幕截圖](http://matplotlib.sourceforge.net/users/screenshots.html) ### 1.4.5.3 代碼文檔 代碼都有很好的文檔,你可以在Python會話中用特定命令很快的訪問: In?[3]: ``` import pylab as pl help(pl.plot) ``` ``` Help on function plot in module matplotlib.pyplot: plot(*args, **kwargs) Plot lines and/or markers to the :class:`~matplotlib.axes.Axes`. *args* is a variable length argument, allowing for multiple *x*, *y* pairs with an optional format string. For example, each of the following is legal:: plot(x, y) # plot x and y using default line style and color plot(x, y, 'bo') # plot x and y using blue circle markers plot(y) # plot y using x as index array 0..N-1 plot(y, 'r+') # ditto, but with red plusses If *x* and/or *y* is 2-dimensional, then the corresponding columns will be plotted. An arbitrary number of *x*, *y*, *fmt* groups can be specified, as in:: a.plot(x1, y1, 'g^', x2, y2, 'g-') Return value is a list of lines that were added. By default, each line is assigned a different color specified by a 'color cycle'. To change this behavior, you can edit the axes.color_cycle rcParam. The following format string characters are accepted to control the line style or marker: ================ =============================== character description ================ =============================== ``'-'`` solid line style ``'--'`` dashed line style ``'-.'`` dash-dot line style ``':'`` dotted line style ``'.'`` point marker ``','`` pixel marker ``'o'`` circle marker ``'v'`` triangle_down marker ``'^'`` triangle_up marker ``'<'`` triangle_left marker ``'>'`` triangle_right marker ``'1'`` tri_down marker ``'2'`` tri_up marker ``'3'`` tri_left marker ``'4'`` tri_right marker ``'s'`` square marker ``'p'`` pentagon marker ``'*'`` star marker ``'h'`` hexagon1 marker ``'H'`` hexagon2 marker ``'+'`` plus marker ``'x'`` x marker ``'D'`` diamond marker ``'d'`` thin_diamond marker ``'|'`` vline marker ``'_'`` hline marker ================ =============================== The following color abbreviations are supported: ========== ======== character color ========== ======== 'b' blue 'g' green 'r' red 'c' cyan 'm' magenta 'y' yellow 'k' black 'w' white ========== ======== In addition, you can specify colors in many weird and wonderful ways, including full names (``'green'``), hex strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or grayscale intensities as a string (``'0.8'``). Of these, the string specifications can be used in place of a ``fmt`` group, but the tuple forms can be used only as ``kwargs``. Line styles and colors are combined in a single format string, as in ``'bo'`` for blue circles. The *kwargs* can be used to set line properties (any property that has a ``set_*`` method). You can use this to set a line label (for auto legends), linewidth, anitialising, marker face color, etc. Here is an example:: plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2) plot([1,2,3], [1,4,9], 'rs', label='line 2') axis([0, 4, 0, 10]) legend() If you make multiple lines with one plot command, the kwargs apply to all those lines, e.g.:: plot(x1, y1, x2, y2, antialised=False) Neither line will be antialiased. You do not need to use format strings, which are just abbreviations. All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with:: plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12). See :class:`~matplotlib.lines.Line2D` for details. The kwargs are :class:`~matplotlib.lines.Line2D` properties: agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) animated: [True | False] antialiased or aa: [True | False] axes: an :class:`~matplotlib.axes.Axes` instance clip_box: a :class:`matplotlib.transforms.Bbox` instance clip_on: [True | False] clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] color or c: any matplotlib color contains: a callable function dash_capstyle: ['butt' | 'round' | 'projecting'] dash_joinstyle: ['miter' | 'round' | 'bevel'] dashes: sequence of on/off ink in points drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] figure: a :class:`matplotlib.figure.Figure` instance fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] gid: an id string label: string or anything printable with '%s' conversion. linestyle or ls: [``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``] linewidth or lw: float value in points lod: [True | False] marker: unknown markeredgecolor or mec: any matplotlib color markeredgewidth or mew: float value in points markerfacecolor or mfc: any matplotlib color markerfacecoloralt or mfcalt: any matplotlib color markersize or ms: float markevery: unknown path_effects: unknown picker: float distance in points or callable pick function ``fn(artist, event)`` pickradius: float distance in points rasterized: [True | False | None] sketch_params: unknown snap: unknown solid_capstyle: ['butt' | 'round' | 'projecting'] solid_joinstyle: ['miter' | 'round' | 'bevel'] transform: a :class:`matplotlib.transforms.Transform` instance url: a url string visible: [True | False] xdata: 1D array ydata: 1D array zorder: any number kwargs *scalex* and *scaley*, if defined, are passed on to :meth:`~matplotlib.axes.Axes.autoscale_view` to determine whether the *x* and *y* axes are autoscaled; the default is *True*. Additional kwargs: hold = [True|False] overrides default hold state ``` ### 1.4.5.4 畫廊 當你搜索如何提供一個特定圖片時,[matplotlib畫廊](http://matplotlib.sourceforge.net/gallery.html)也非常有用。每個例子都有源碼。 [這里](http://www.loria.fr/~rougier/coding/gallery/)有一個小的畫廊。 ### 1.4.5.5 郵件列表 最后,你可以在[用戶郵件列表](https://lists.sourceforge.net/lists/listinfo/matplotlib-users)尋求幫助,而[開發者郵件列表](https://lists.sourceforge.net/lists/listinfo/matplotlib-devel)則更偏技術。 ## 1.4.6 快速參考 這里是一組表格,顯示了主要的屬性和樣式。 ### 1.4.6.1 Line屬性 | 屬性 | 描述 | 外觀 | | --- | --- | --- | | alpha (or a) | alpha 0-1范圍的透明度 | ![plot_alpha_1.png](http://scipy-lectures.github.io/_images/plot_alpha_1.png) | | antialiased | True or False - use antialised rendering | ![plot_aliased_1.png](http://scipy-lectures.github.io/_images/plot_aliased_1.png) ![plot_antialiased_1.png](http://scipy-lectures.github.io/_images/plot_antialiased_1.png) | | color (or c) | matplotlib顏色參數 | ![plot_color_1.png](http://scipy-lectures.github.io/_images/plot_color_1.png) | | linestyle (or ls) | see [Line屬性](#line-properties) | | linewidth (or lw) | 浮點, 線寬度用小數表示 | ![plot_linewidth_1.png](http://scipy-lectures.github.io/_images/plot_linewidth_1.png) | | solid_capstyle | 實線頭的樣式 | ![plot_solid_capstyle_1.png](http://scipy-lectures.github.io/_images/plot_solid_capstyle_1.png) | | solid_joinstyle | 實線的連接樣式 | ![plot_solid_joinstyle_1.png](http://scipy-lectures.github.io/_images/plot_solid_joinstyle_1.png) | | dash_capstyle | 虛線頭的樣式 | ![plot_dash_capstyle_1.png](http://scipy-lectures.github.io/_images/plot_dash_capstyle_1.png) | | dash_joinstyle | 虛線的連接樣式 | ![plot_dash_joinstyle_1.png](http://scipy-lectures.github.io/_images/plot_dash_joinstyle_1.png) | | marker | see [標記](#markers) | | markeredgewidth (mew) | 標記符號的線寬度 | ![plot_mew_1.png](http://scipy-lectures.github.io/_images/plot_mew_1.png) | | markeredgecolor (mec) | 標記邊緣的顏色 | ![plot_mec_1.png](http://scipy-lectures.github.io/_images/plot_mec_1.png) | | markerfacecolor (mfc) | 標記的填充顏色 | ![plot_mfc_1.png](http://scipy-lectures.github.io/_images/plot_mfc_1.png) | | markersize (ms) | 標記的大小,以小數表示 | ![plot_ms_1.png](http://scipy-lectures.github.io/_images/plot_ms_1.png) | ### 1.4.6.2 線樣式 ![plot_linestyles_1.png](http://scipy-lectures.github.io/_images/plot_linestyles_1.png) ### 1.4.6.3 標記 ![plot_markers_1.png](http://scipy-lectures.github.io/_images/plot_markers_1.png) ### 1.4.6.4 Colormaps 所有colormap都可以通過添加`_r`來進行顏色反轉。例如`gray_r`是`gray`的補色。 如果你想要更多了解colormaps,檢查一下[matplotlib colormaps的文檔](https://gist.github.com/2719900) ![plot_colormaps_1.png](http://scipy-lectures.github.io/_images/plot_colormaps_1.png)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看