matplotlib繪圖

轉自:https://wklchris.github.io/php

Python科學計算:matplotlib

Py-compute 系列博文

Tips: 雙擊 Ctrl 或點擊頁面右下圖標進行站內搜索;Esc 退出搜索。Double press CTRL or click the icon in the bottomright to search within the whole blog website. ESC to exit searching.spring

本站已加入 Google 索引:site: (https://wklchris.github.io) This site can be accessed via Google search.shell

【目錄ToC】

點擊以跳轉bootstrap

  1. 繪製與保存

    1. 基礎繪圖:plt.plot

    2. 多圖繪製:plt.subplots

    3. 圖像保存

    4. 顏色

    5. rcParams:默認參數

  2. 圖像控制

    1. 圖像、座標軸標題:Axes.set_title / set_x(y)label

    2. 座標軸命令:

    3. 座標軸框架:Axes.spines

    4. 圖例:Axes.legend

    5. 刻度與刻度標籤:Axes.set_x(y)ticks / x(y)ticklabels

    6. 添加文字:Axes.text / annotate

    7. 網格:Axes.grid

  3. 圖像繪製

    1. 水平豎直線或區域:Axes.axhline / axhspan

    2. 散點圖:Axes.scatter

    3. 條形圖:Axes.bar / barh

    4. 直方圖:Axes.hist

    5. 箱形圖:Axes.boxplot

    6. 等高線圖:Axes.contour(f)

  4. 其餘命令

    1. 填充:Axes.fill_between / fill_betweenx

    2. 對數座標軸:Axes.loglog / semilogx / semilogy

    3. 極座標

    4. 左手座標系

  5. 附:GIF 動態圖保存

    1. 前提工做

    2. 例子

若是您的設備分辨率太低,或網頁窗寬度太小,您可能看不到目錄邊欄。If your are using a low resolution device or viewing via a narrow webbrowser window, you might not see the sidebar.



 

本文介紹 matplotlib 相關的內容,以例子爲主。

全文的初始化加載以下:

import osimport numpy as npimport pandas as pdimport matplotlib as mplfrom matplotlib import pyplot as pltfrom numpy.random import rand

本文最後編輯時,使用的各版本號以下:

np.__version__, pd.__version__, mpl.__version__
('1.12.1', '0.19.2', '2.0.1')

繪製與保存

 

基礎繪圖:plt.plot

基礎的繪圖使用 plt.plot() 命令,並用 plt.show() 顯示。

# 向量經常使用 linspace 或者 arange 命令進行初始化。下兩例等價:# np.linspace(0, 4, 4):閉區間 [0,4] 上等距取 4 個點# np.arange(0, 5, 1):左閉右開區間 [0, 5) 上以步長 1 取點x = np.linspace(0, 4, 100)y1 = x ** 2y2 = 2 * x + 3plt.plot(x, y1, color="b", linestyle=":", linewidth=3, dashes=(2,1),  # 線的屬性
         marker="d", ms=10, mew=1.5, mec="g", mfc="w",  # 點的屬性
         markevery=10)plt.plot(x, y2, "#bf242a", ls="-", lw=1)plt.show()

png

一些經常使用的性質:

  • color:線的顏色。基礎的有紅r,綠g,藍b,青c,洋紅m,黃y,黑k,白w。參考本節的「顏色」小節。

    • 一些其餘的顏色表述:color=」#66ccff」 HTML碼;(1, 0, 0) 標準化的RGB元組;」0.5」 灰度字串。

  • linestyle(ls):線型。實線」-「,虛線」–「,點劃線」-.」,點線」:」。

    • dashes: 虛線比例。傳入元組 (a,b),那麼劃線長與間隔長之比爲 a/b。

  • linewidth(lw):線寬。

  • marker:點樣式。實心」.」,像素」,」,圓點」o」,方塊」s」,上折/下折箭頭」v」/」\^」,左折/右折箭頭」<」/」>」,五邊形」p」,六邊形」h」,星」*「,加號」+」,叉號」x」,(瘦)鑽石」d/D」,豎線」‘|「,橫線」_「。

    • markevery:每幾個點才繪製一個點。

    • markersize(ms):點大小。

    • markeredgewidth(mew):點邊緣線寬。

    • markeredgecolor(mec):點邊緣顏色。默認與線同色。

    • markerfacecolor(mfc):點填充顏色。默認與線同色。

另外介紹 plt.close() 命令。一般用 plt.close("all") 來關閉全部的圖片。

多圖繪製:plt.subplots

上面的內容我稱之爲基礎繪製,是一種多語句排列、最後用 plt.show() 命令轉換爲圖像輸出的方式。而下文要介紹的命令,大可能是基於多圖繪製的,會事先聲明總圖(figure對象)與全部子圖句柄(Axes對象)

例如 plt.title() 命令是基礎繪製中的命令,直接調用自 matplotlib.pyplot 裏的命令。而在多圖繪製下,則是先生成一種子圖的實例 ax,再從實例中調用一個等價的函數 ax.set_title() 。

# 該例子改編自:http://matplotlib.org/examples/pylab_examples/subplots_demo.htmlx = np.linspace(0, 4 * np.pi, 400)y1 = np.sin(x)y2 = np.sin(2 * x)y3 = np.sin(4 * x)y = [y1, y2, y3]plt.close("all")# f, (ax1, ax2, ax3) = ... 也是一種寫法f, axarr = plt.subplots(3, sharex=True, sharey=True)f.subplots_adjust(hspace=0)  # 調整函數# 若是是多行多列,可使用 axarr = axarr.ravel() 再以 for 遍歷for i in range(len(y)):
    axarr[i].plot(x, y[i])plt.show()

png

plt.subplots() 是一個實用的命令:

  • nrows, ncols:子圖的行數與列數。默認爲 1. 上例的 subplots(3) 至關於 subplots(3, 1)。

  • sharex, sharey:軸對齊True,不對齊False,每行對齊」row」,每列對齊」col」。

有些參數能夠直接在 subplots 中使用,但其實會進一步傳遞給其餘函數。一併在這裏介紹:

  • figsize:元組。總圖的長與寬。

  • subplot_kw:傳遞給命令 add_subplot() 的參數,經常使用的是極座標 dict(projection=’polar’)。

  • gridspec_kw:字典。給出各列/行子圖之間的寬/長之比,例如「條形圖」一節:gridspec_kw={‘height_ratios’:[1, 2]}。

調整函數 subplots_adjust 是一個視覺命令:

  • left, right, bottom, top:間距。

  • hspace,wspace:縱向/橫向間距。

圖像保存

多圖繪製一個便利之處在於,已經將圖像存儲在了聲明的 Figure 對象中。例如對於上一節的例子:

filename = r'd:\test.pdf'  # 這一步經常配合 os.getcwd() 來獲取工做目錄,再保存圖片f.savefig(filename, transparent='True', format='pdf')

若是是 png 格式,還能夠用 dpi=… 參數標定其圖片質量。

有時候咱們須要操做動態圖;對於動態圖 GIF 的保存,請參考本文附錄

顏色

matplotlib 中的顏色支持用如下的方式指定:

  • 標準化的 RGB:以三元元組的形式,好比 (0, 0, 1) 表明 (0, 0, 255),即純藍。

  • HTML 16進制顏色碼:以字符串的形式,好比 "#0F0F0F}"

  • 標準化的灰度值:以字符串形式,好比 0.5 。

  • RGB 與 CMYK 標準色字符:以單個字符形式,有:r,g,b,c,m,y,k,w 八種,其中 w 是白色。

  • X11/CSS4 標準的顏色名:

  • XKCD 顏色調查(參考此頁面):例如」xksd:sky blue」。

以及 matplotlib 採用的:

  • matplotlib 默認的十色環:」C0」, 「C1」, ……,」C9」。這是 matplotlib 繪圖默認依次使用的顏色。

  • 十色環的另外一種形式:’tab:blue’, ‘tab:orange’, ‘tab:green’, ‘tab:red’, ‘tab:purple’, ‘tab:brown’, ‘tab:pink’, ‘tab:gray’, ‘tab:olive’, ‘tab:cyan’。

以上字符串(除16進制碼外)均是大小寫敏感的。

# A list of X11 color names from: http://cng.seas.rochester.edu/CNG/docs/x11color.html# Total 140 colors included.colors = [("LightPink", "#FFB6C1"),("Pink", "#FFC0CB"),("Crimson", "#DC143C"),("LavenderBlush", "#FFF0F5"),
          ("PaleVioletRed", "#DB7093"),("HotPink", "#FF69B4"),("DeepPink", "#FF1493"),("MediumVioletRed", "#C71585"),        
          ("Orchid", "#DA70D6"),("Thistle", "#D8BFD8"),("Plum", "#DDA0DD"),("Violet", "#EE82EE"),                            
          ("Magenta", "#FF00FF"),("Fuchsia", "#FF00FF"),("DarkMagenta", "#8B008B"),("Purple", "#800080"),                    
          ("MediumOrchid", "#BA55D3"),("DarkViolet", "#9400D3"),("DarkOrchid", "#9932CC"),("Indigo", "#4B0082"),             
          ("BlueViolet", "#8A2BE2"),("MediumPurple", "#9370DB"),("MediumSlateBlue", "#7B68EE"),("SlateBlue", "#6A5ACD"),     
          ("DarkSlateBlue", "#483D8B"),("Lavender", "#E6E6FA"),("GhostWhite", "#F8F8FF"),("Blue", "#0000FF"),                
          ("MediumBlue", "#0000CD"),("MidnightBlue", "#191970"),("DarkBlue", "#00008B"),("Navy", "#000080"),                 
          ("RoyalBlue", "#4169E1"),("CornflowerBlue", "#6495ED"),("LightSteelBlue", "#B0C4DE"),("LightSlateGray", "#778899"),
          ("SlateGray", "#708090"),("DodgerBlue", "#1E90FF"),("AliceBlue", "#F0F8FF"),("SteelBlue", "#4682B4"),              
          ("LightSkyBlue", "#87CEFA"),("SkyBlue", "#87CEEB"),("DeepSkyBlue", "#00BFFF"),("LightBlue", "#ADD8E6"),            
          ("PowderBlue", "#B0E0E6"),("CadetBlue", "#5F9EA0"),("Azure", "#F0FFFF"),("LightCyan", "#E0FFFF"),                  
          ("PaleTurquoise", "#AFEEEE"),("Cyan", "#00FFFF"),("Aqua", "#00FFFF"),("DarkTurquoise", "#00CED1"),                 
          ("DarkSlateGray", "#2F4F4F"),("DarkCyan", "#008B8B"),("Teal", "#008080"),("MediumTurquoise", "#48D1CC"),           
          ("LightSeaGreen", "#20B2AA"),("Turquoise", "#40E0D0"),("Aquamarine", "#7FFFD4"),("MediumAquamarine", "#66CDAA"),   
          ("MediumSpringGreen", "#00FA9A"),("MintCream", "#F5FFFA"),("SpringGreen", "#00FF7F"),("MediumSeaGreen", "#3CB371"),
          ("SeaGreen", "#2E8B57"),("Honeydew", "#F0FFF0"),("LightGreen", "#90EE90"),("PaleGreen", "#98FB98"),                
          ("DarkSeaGreen", "#8FBC8F"),("LimeGreen", "#32CD32"),("Lime", "#00FF00"),("ForestGreen", "#228B22"),               
          ("Green", "#008000"),("DarkGreen", "#006400"),("Chartreuse", "#7FFF00"),("LawnGreen", "#7CFC00"),                  
          ("GreenYellow", "#ADFF2F"),("DarkOliveGreen", "#556B2F"),("YellowGreen", "#9ACD32"),("OliveDrab", "#6B8E23"),      
          ("Beige", "#F5F5DC"),("LightGoldenrodYellow", "#FAFAD2"),("Ivory", "#FFFFF0"),("LightYellow", "#FFFFE0"),          
          ("Yellow", "#FFFF00"),("Olive", "#808000"),("DarkKhaki", "#BDB76B"),("LemonChiffon", "#FFFACD"),                   
          ("PaleGoldenrod", "#EEE8AA"),("Khaki", "#F0E68C"),("Gold", "#FFD700"),("Cornsilk", "#FFF8DC"),                     
          ("Goldenrod", "#DAA520"),("DarkGoldenrod", "#B8860B"),("FloralWhite", "#FFFAF0"),("OldLace", "#FDF5E6"),           
          ("Wheat", "#F5DEB3"),("Moccasin", "#FFE4B5"),("Orange", "#FFA500"),("PapayaWhip", "#FFEFD5"),                      
          ("BlanchedAlmond", "#FFEBCD"),("NavajoWhite", "#FFDEAD"),("AntiqueWhite", "#FAEBD7"),("Tan", "#D2B48C"),           
          ("BurlyWood", "#DEB887"),("Bisque", "#FFE4C4"),("DarkOrange", "#FF8C00"),("Linen", "#FAF0E6"),                     
          ("Peru", "#CD853F"),("PeachPuff", "#FFDAB9"),("SandyBrown", "#F4A460"),("Chocolate", "#D2691E"),                   
          ("SaddleBrown", "#8B4513"),("Seashell", "#FFF5EE"),("Sienna", "#A0522D"),("LightSalmon", "#FFA07A"),               
          ("Coral", "#FF7F50"),("OrangeRed", "#FF4500"),("DarkSalmon", "#E9967A"),("Tomato", "#FF6347"),                     
          ("MistyRose", "#FFE4E1"),("Salmon", "#FA8072"),("Snow", "#FFFAFA"),("LightCoral", "#F08080"),                      
          ("RosyBrown", "#BC8F8F"),("IndianRed", "#CD5C5C"),("Red", "#FF0000"),("Brown", "#A52A2A"),                         
          ("FireBrick", "#B22222"),("DarkRed", "#8B0000"),("Maroon", "#800000"),("White", "#FFFFFF"),                        
          ("WhiteSmoke", "#F5F5F5"),("Gainsboro", "#DCDCDC"),("LightGrey", "#D3D3D3"),("Silver", "#C0C0C0"),                 
          ("DarkGray", "#A9A9A9"),("Gray", "#808080"),("DimGray", "#696969"),("Black", "#000000")]                           plt.close("all")f, ax = plt.subplots(figsize=(15, 12))w, h = 10, 4rowpad, colpad = 2, 9 for i in range(140):
    curname = colors[i][0]
    cols, rows = divmod(i, 35)
    rows = 34 - rows
    ax.fill_between([w * cols, w * (cols + 1) - colpad],
                    [h * rows, h * rows], 
                    [h * (rows + 1) - rowpad, h * (rows + 1) - rowpad],
                    facecolor=curname)
    ax.text(w * (cols + 1) - 0.95*colpad, h * rows + (h - rowpad) / 2, "{}, {}".format(*colors[i]), 
            horizontalalignment="left", verticalalignment='center')ax.axis(xmax=4*w)ax.set_axis_off()ax.set_title("X11 colors table", fontsize=16)
    plt.show()

png

rcParams:默認參數

從上面的繪圖中能夠看到,即便沒有指定線型、點樣式,matplotlib 也能以其默認的顏色、樣式繪圖。這些默認參數是能夠修改的。它們都存儲在 matplotlib.rcParams 這個大字典變量中。例如默認的線顏色:

mpl.rcParams["lines.color"]
'C0'

使用 rc 命令來更改默認參數的值,例以下例將更改 mpl.rcParams["lines.linewidth"] 與 mpl.rcParams["lines.color"] 兩個鍵值:

# 更改默認的值:# mpl.rc('lines', linewidth=2, color='r')# 僅在接下來繪製的圖片中應用值:# plt.rc(...)

一個繪圖的例子:

from cycler import cyclern = 6line_num = 8x = np.linspace(0, 2 * np.pi, n)np.random.seed(0)y = np.random.rand(line_num, n)plt.close("all")f, ax = plt.subplots()plt.rc("lines", linewidth=2)plt.rc("axes", prop_cycle=(cycler('color', ['Salmon', 'Orange', 
                                            'SeaGreen', 'DodgerBlue']) +
                           cycler('linestyle', ['-', '--', ':', '-.'])))for i in range(line_num):
    ax.plot(x, y[i], label="Line {}".format(i+1))ax.legend(loc="lower left", ncol=4)plt.show()

png

要想下面的圖片繪製不受影響,使用如下命令恢復默認值:

mpl.rcParams.update(mpl.rcParamsDefault)

圖像控制

 

下面介紹一些經常使用的控制參數,如座標軸區間、標籤、標題文字等等。

圖像、座標軸標題:Axes.set_title / set_x(y)label

設置標題時能夠傳入字體參數字典 fontdict (或者將其中的鍵單獨傳遞,以下例),默認值是:

{'fontsize': rcParams['axes.titlesize'],
 'fontweight' : rcParams['axes.titleweight'],
 'verticalalignment': 'baseline',
 'horizontalalignment': loc}

座標軸標題 set_xlabel/set_ylabel 可使用 labelpad 參數,設定到座標軸的距離的倍數值。

若是要設定標題到圖像的距離,使用 set_title 的 y 參數 ,例如 y = 1.05.

x = np.linspace(0, 2 * np.pi, 1000)y = np.sin(x)plt.close("all")f, ax = plt.subplots()ax.plot(x, y)ax.set_title(r"Title even support LaTeX: $\alpha\geq\beta$", loc="left", fontsize=12)ax.set_xlabel("This is a X far from x-axis!", labelpad=20)ax.set_ylabel("This is a small fontsize Y!", fontsize=8)plt.show()

png

座標軸命令:

座標軸命令有不少:

  1. 設置座標軸區間:Axes.axis,能夠經過選項 xmin/xmax/ymin/ymax 指定單側邊界。

  2. 設置單軸區間:Axes.set_xlim/ylim

  3. 顯示、隱藏座標軸:Axes.set_axis_on/off

  4. 隱藏座標框:Axes.set_frame_on,傳入 False 以隱藏。

  5. 設置座標軸背景色:Axes.set_facecolor,傳入顏色字符串。

x = np.linspace(0, 2 * np.pi, 1000)y = np.sin(x)titles = ["Default", "Default without axes", "Default without frames",
          "Given all boundaries", "Given Xmax only", 
          "X-limit with background color"]plt.close("all")f, axarr = plt.subplots(2, 3, figsize=(15, 6))f.subplots_adjust(hspace=0.35, wspace=0.35)axarr = axarr.ravel()for ax, t in zip(axarr, titles):
    ax.plot(x, y)
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_title(t)# axarr[0]:defaultaxarr[1].set_axis_off()axarr[2].set_frame_on(False)axarr[3].axis([0, 7, -1.5, 1.5])axarr[4].axis(xmax=2 * np.pi)axarr[5].set_xlim([1, 5])axarr[5].set_facecolor("lightgreen")plt.show()

png

座標軸框架:Axes.spines

座標軸框架能夠設置其可見性與否 set_visible,而且移動其位置。

x = np.linspace(-1, 3, 1000)y = x ** 2plt.close('all')fig, ax = plt.subplots()ax.plot(x, y)ax.set_xlabel("X")ax.set_ylabel("Y")ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)ax.spines['bottom'].set_position(('data', 0))ax.spines['left'].set_position(('data', 0))ax.axis([-1, 2, -2, 6])plt.show()

png

圖例:Axes.legend

圖例配合 plot 函數的 label 參數使用,文字部分會直接使用 label 參數的字串。圖例放置位置由 loc 參數指定,具體的取值有:

  • 自動‘best’或0

  • 右上‘upper right’或1

  • 左上‘upper left’或2,左下‘lower left’或3,左中‘center left’或6

  • 右下‘lower right’或4,右側‘right’5,右中‘center right’或7

  • 中下‘lower center’或8,中上‘upper center’或9,中部‘center’或10。

並能夠結合 bbox_to_anchor 參數靈活地設置對齊參考,甚至放置在圖框外側。

圖例由圖線(handle)與文字(text)兩部分組成,每對圖線與文字組成一個標籤(label)。由此理解:borderpadlabelspacinghandlelengthhandletextpadborderaxespadcolumnspacing 這些空距控制參數。注意:borderpad是一個比例值。

其餘參數參考下面的例子。

x = np.linspace(0, 2 * np.pi, 30)y1, y2 = np.sin(x), np.cos(x)titles = ["Simple legend", "Legend with more and larger markers", 
          "Legend outside the figure frame",
          "Legend with a title but no frame",
          "Legend with face & edge color",
          "Legend with adjusted size & spacings"]plt.close("all")f, axarr = plt.subplots(2, 3, sharey=True, figsize=(15, 8))f.subplots_adjust(hspace=0.35)axarr = axarr.ravel()for ax, t in zip(axarr, titles):
    ax.plot(x, y1, "o-", label=r"$y=\sin x$")
    ax.plot(x, y2, "s--", label=r"$y=\cos x$")
    ax.set_title(t)axarr[0].legend(loc="lower left")axarr[1].legend(numpoints=2, markerscale=1.5, fontsize=14)axarr[2].legend(loc="upper center", ncol=2, bbox_to_anchor=(0.5, -0.08))axarr[3].legend(frameon=False, title="LgTitle")axarr[4].legend(facecolor="lightgreen", edgecolor="k")axarr[5].legend(handlelength=3, handletextpad=0.5,
                labelspacing=1, columnspacing=1)plt.show()

png

刻度與刻度標籤:Axes.set_x(y)ticks / x(y)ticklabels

刻度標籤字符串的格式如何修改,也在下例中給出。

附註:方法 Axes.set_xticks 與 Axes.xaxis.set_ticks 是等價的。

from matplotlib.ticker import FormatStrFormatterimport stringnp.random.seed(0)x, y = np.random.rand(2, 100)titles = ["Default ticks", "Given ticks", 
          "Given ticks and their format", "Given ticklabels"]xticksnum, yticksnum = 10, 5xticks = np.linspace(0, 1, xticksnum + 1)yticks = np.linspace(0, 1, yticksnum + 1)plt.close("all")f, axarr = plt.subplots(2, 2, figsize=(15, 7))axarr =axarr.ravel()for i in range(4):
    ax = axarr[i]
    ax.plot(x, y, "o")
    ax.set_title(titles[i])
    ax.axis([0, 1, 0, 1])
    if i > 0:
        ax.set_xticks(xticks)
        ax.set_yticks(yticks)
    axarr[2].xaxis.set_major_formatter(FormatStrFormatter('%0.2f'))axarr[3].set_xticklabels(string.ascii_uppercase[:xticksnum + 1])axarr[3].set_yticklabels([])  # y 軸刻度標籤留空plt.show()

png

添加文字:Axes.text / annotate

一個簡明的 text 命令的例子:

# 本例改編自:http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.text.htmlplt.close("all")plt.plot([1 , 1], [0, 3], color='k', linewidth=0.5 , linestyle='--')# 單獨使用字號控制命令plt.text(2, 1, 'Hmm', fontsize=12)  # 使用字典形式的字體控制plt.text(1, 1, 'Two lines \n text ', horizontalalignment='center', 
         fontdict={'size': 12, 'color': 'r'})  # bbox 是一個複雜的參數,在此很少深刻plt.text(1, 3, 'With box', bbox=dict(facecolor='r', alpha=0.3))  plt.axis([0, 3, 0, 4])plt.show()

png

annotate 的例子:

plt.close('all')f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))ax1.plot([0, 10], [0, 15], 'b')ax1.annotate(r'A text', xy=(6,8), xytext=(20, -30), textcoords='offset pixels', 
             arrowprops=dict(arrowstyle='->'))ax2.plot([0, 10], [0, 15], 'r')ax2.annotate(r'Another', xy=(6,8), xytext=(10, -60), 
             textcoords='offset pixels', fontsize=12, 
             # 指定圓弧半徑,負值表示順時針畫弧
             arrowprops=dict(arrowstyle='-|>',
                             connectionstyle='arc3, rad=-0.3'))  plt.show()

png

上例中,arrowprops 要傳入一個字典。該字典的 arrowwstyle 鍵可選的值(大體都是象形的,再也不註釋中文含義)有:

arrowstyle 參數 等效參數形式
’-‘ None
’->’ head_length=0.4,head_width=0.2
’-[’ widthB=1.0,lengthB=0.2,angleB=None
‘|-|’ widthA=1.0,widthB=1.0
’-|>’ head_length=0.4,head_width=0.2
’<-‘ head_length=0.4,head_width=0.2
’<->’ head_length=0.4,head_width=0.2
’<|-‘ head_length=0.4,head_width=0.2
’<|-|>’ head_length=0.4,head_width=0.2

connectionstyle 鍵可選的值:

connectionstyle 參數 等效參數形式
angle angleA=90,angleB=0,rad=0.0
angle3 angleA=90,angleB=0
arc angleA=0,angleB=0,armA=None,armB=None,rad=0.0
arc3 rad=0.0
bar armA=0.0,armB=0.0,fraction=0.3,angle=None

網格:Axes.grid

一個基礎的例子:

x = np. linspace (0, 10, 100)y = 2 * np.sin(x)plt.close("all")plt.plot(x, y)# 其實簡單地使用 "plt.grid(True)"  就能夠顯示網格plt.grid(axis='y', linestyle='--', color='0.75')  # 灰度適當很重要plt.show()

png

下例給出了網格線的繪製步驟,以及主要、次要網格線分開設置的方法。

from matplotlib.ticker import MultipleLocator, FormatStrFormatterx = np. linspace (0, 10, 100)y = 2*xplt.close('all')fig, ax = plt.subplots()ax.plot(x, y)ax.xaxis.set_major_locator(MultipleLocator(2))ax.yaxis.set_major_locator(MultipleLocator(5))ax.xaxis.set_minor_locator(MultipleLocator(1))ax.yaxis.set_minor_locator(MultipleLocator(1))ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))ax.grid(which='major', linestyle='-', color='k')ax.grid(which='minor', linestyle='--', color='r', alpha=0.2)ax.axis([0, 10, 0, 20])plt.show()

png

圖像繪製

 

下面介紹不一樣種類的圖像的繪製,如條形圖、散點圖等等。

水平豎直線或區域:Axes.axhline / axhspan

參數:圖像中座標軸的百分比位置 xmin/xmax/ymin/ymax。

plt.close("all")f, ax = plt.subplots()ax.axis([0, 3, 0, 2])ax.axhline(1, lw=8, color='g')ax.axhline(y=1.5, ls="--", lw=2, xmin=0.25, xmax=0.75)ax.axvline(2.5, color="y")ax.axhspan(0.25, 0.75, xmin=0.25, facecolor='0.5')ax.axvspan(0.5, 1.5, facecolor="#74D2D5", alpha=0.2)plt.show()

png

散點圖:Axes.scatter

參數:點大小向量s,點顏色向量c,透明度alpha。

此外,直接使用 plot命令能夠繪製簡單的點圖。只要不指定線屬性,繪圖時就只繪製點而不繪製線。

np.random.seed(230)x, y = np.random.rand(2, 10)np.random.seed(666)point_size = 1000 * rand(10)plt.close("all")f, ax = plt.subplots()ax.scatter(x, y, s=point_size, c=["b", "r"] * 5, alpha=0.5)plt.show()

png

條形圖:Axes.bar / barh

條形圖命令 bar 用於繪製豎立的條形圖,而 barh 用於繪製水平的。

在 Axes.bar(left, height, width=0.8, bottom=None, **kwargs) 命令中,條形的繪製區域是 [left +/- width], [bottom, bottom + height]。利用 yerr 與 error_kw 參數,能夠繪製 error 線在條形圖中。

bar_width = 0.35groups = np.arange(5)y1 = np.linspace(10, 50, 5)np.random.seed(0)y2 = np.random.rand(5) * 40 + 10 plt.close("all")f, ax = plt.subplots(2, 2, figsize=(14, 6), gridspec_kw = {'height_ratios':[1, 2]})# 並列豎立條形圖ax[0,0].bar(groups, y1, bar_width, label="Class 1",
          yerr=2 * groups + 1)ax[0,0].bar(groups + bar_width, y2, bar_width, label="Class 2")ax[0,0].set_xticks(groups + bar_width / 2)ax[0,0].set_xticklabels(list("ABCDE"))ax[0,0].legend(loc="upper left")# 堆疊豎立條形圖ax[0,1].bar(groups, y1, bar_width, label="Class 1")ax[0,1].bar(groups, y2, bar_width, bottom=y1, label="Class 2")ax[0,1].set_xticks(groups)ax[0,1].set_xticklabels(list("ABCDE"))ax[0,1].legend(loc="upper left")# 橫置條形圖ax[1,0].barh(groups, y1, bar_width, label="Class 1")ax[1,0].barh(groups + bar_width, y2, bar_width, label="Class 2")ax[1,0].set_yticks(groups + bar_width / 2)ax[1,0].set_yticklabels(list("ABCDE"))ax[1,0].legend(loc="lower right")# 堆疊豎立百分比條形圖(附百分比數字)y1_percent = y1 / (y1 + y2)y2_percent = y2 / (y1 + y2)ax[1,1].bar(groups, y1_percent, bar_width, label="Class 1")ax[1,1].bar(groups, y2_percent, bar_width, bottom=y1_percent, label="Class 2")## 加上百分比字串for k in range(len(groups)):
    ax[1,1].text(groups[k], y1_percent[k]/2, r"{:.0%}".format(y1_percent[k]),
                 color="w", ha="center", va="center")
    ax[1,1].text(groups[k], y2_percent[k]/2 + y1_percent[k], 
                 r"{:.0%}".format(y2_percent[k]), color="k", ha="center", va="center")ax[1,1].set_xticks(groups)ax[1,1].set_xticklabels(list("ABCDE"))ax[1,1].legend(loc="center left", bbox_to_anchor=(1.0, 0.5))## 設置 y 軸刻度ax[1,1].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(
                                  lambda y, pos: r"{:.0f}%".format(100*y)))plt.show()

png

直方圖:Axes.hist

參數:histtype 能夠指定爲 「bar」(默認)或者 「barstacked」, 「step」, 「stepfilled」 四種類型,其中 「barstacked」 與 「bar」 參數外加 「stacked=True」 的效果是同樣的。rwidth 能夠指定每組的柱形寬度佔組寬的多少。normed 參數用於控制標準化,使各條形面積總和爲 1。weights 參數用於添加計數權重,尺寸與數據尺寸一致。最後,color 參數來傳入一個控制顏色的元組。

np.random.seed(0)x = np.random.rand(100, 3)bins_num = 10plt.close("all")f, ax = plt.subplots(2, 2, sharex=True, figsize=(12, 8))ax[0,0].hist(x, bins_num)ax[0,0].set_title("Simple")ax[0,1].hist(x, bins_num, histtype="bar", stacked=True, rwidth=0.5)ax[0,1].set_title("Stacked histogram")ax[1,0].hist(x, bins_num, normed=True)ax[1,0].set_title("Normalized histogram")ax[1,1].hist(x, bins_num, color=("c", "y", "b"), weights=1/x)ax[1,1].set_title("Weighted histogram")plt.show()

png

箱形圖:Axes.boxplot

箱形圖的參數比較多:

  • labels:字符串列表。做爲分組標籤。

  • width:列表。指定各箱形圖的寬度。

  • vert:默認爲 True。爲 False 時,箱形圖將橫向繪製。

  • whis:數字,列表,或者「range」,用於指定正常值範圍。通常地,箱形圖中會找到低、高兩個四分位點 Q1 與 Q3,並在它們之間(IQR=Q3-Q1)繪製箱形圖的主體。而箱形圖中的高、低的兩個 cap 所肯定的正常值範圍,則是由 Q3 + whis * IQR 與 Q1 - whis * IQR 決定的,其中 whis 的默認值是 1.5。除了給該參數傳入數字,也能夠傳入:

    • 字符串「range」,表示將全部數據點歸入正常值範圍。

    • 數字列表:以 [a, b] 的形式傳入,表示正常值範圍從 a 百分位到 b 百分位。

  • 均值相關的參數:

    • showmeans:布爾型,默認 False。顯示均值。如下參數在 showmean=True 時有效。

    • meanline:布爾型。在箱形圖中繪製一條橫線,表示均值的位置。

    • meanprops:字典。指定均值參數。能夠是點屬性,也能夠是線屬性,參考下例。

  • 中位數相關的參數:

    • medianprops 用法相似均值參數。

    • usermedians傳入一個 n 乘 2 數組,數組中非None的元素會取代對應位置的正常計算的中位數。

  • 箱體相關的參數:showboxboxprops

  • 異常值(flier)、須(whisker)與區間壁(cap)相關的參數:showcapsshowfliersflierpropscapprops, whiskerprops

  • 置信區間參數:

    • notch:布爾型。繪製 V 型(中值處內縮的)箱形圖。

    • conf_intervals :置信區間,n 乘 2 數組(n爲單組數據點個數,下例爲1000)。

    • bootstrap:整數。用自助抽樣法抽取指定個數的樣本,並標註 95% 置信區間。

  • 美化參數:patch_artist 默認 False。若是爲 True,會填充箱形區域,並支持更改顏色。好比 facecolor 參數,它在 patch_artist=False 時是沒法傳入給 boxprops 字典的,由於兩種模式下 boxplot 返回的類型是不一樣的。

# 本例源自:http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.boxplot.htmlmu, sigma = 1, 1/3np.random.seed(0)x = np.random.normal(mu, sigma, size=(1000, 3))# Properties boxprops = dict(linestyle='--', linewidth=3, color='tan')flierprops = dict(marker='o', markerfacecolor='lightgreen', markersize=4,
                  linestyle='none')medianprops = dict(linestyle='-.', linewidth=2.5, color='firebrick')meanpointprops = dict(marker='D', markeredgecolor='black',
                      markerfacecolor='firebrick', markersize=6)meanlineprops = dict(linestyle='--', linewidth=2.5, color='purple')# Plotplt.close("all")f, ax = plt.subplots(2, 3, figsize=(15, 8))ax[0,0].boxplot(x)ax[0,0].set_title("Default boxplot")ax[0,1].boxplot(x, whis=1, labels=list("ABC"),
                patch_artist=True, boxprops = dict(facecolor=("lightblue")))ax[0,1].set_title("Bboxplot with labels and 1X range")ax[0,2].boxplot(x, medianprops=medianprops, whis="range", labels=list("ABC"))ax[0,2].set_title("Boxplot with medianline and\nfull-length whiskers")ax[1,0].boxplot(x, showcaps=False, showfliers=False, labels=list("ABC"),
                showmeans=True, meanline=True, meanprops=meanlineprops,)ax[1,0].set_title("Customized boxplot: meanline")ax[1,1].boxplot(x, showmeans=True, flierprops=flierprops, 
                meanprops=meanpointprops, labels=list("ABC"))ax[1,1].set_title("Customized boxplot: meanpoint")ax[1,2].boxplot(x, vert=False, boxprops=boxprops, labels=list("ABC"))ax[1,2].set_title("Horizontal customized boxplot")plt.show()

png

等高線圖:Axes.contour(f)

contour 有如下幾種調用方法:

  • contour(Z, …)表示在網格上,繪製高度爲 Z 的等高線圖。

  • contour(Z, N, …)表示繪製高度爲 Z 的等高線圖,其等高線總數爲 N 且自動選定。

  • contour(Z, V, …)表示繪製高度爲 Z 的等高線圖,其等高線知足列表 V 指定要繪製等高線的高度位置。

  • 以上全部調用方法以前,都可以加上 X, Y 參數,表示在  X,Y 網格上繪製。

其餘的一些經常使用參數(contour 還可使用 linestyle 與 linewidth):

  • colors:單個字串或一個字串元組。設定等高線顏色。

  • levels:即上述調用方法中的 V 參數。

  • orgin:[當 X,Y 指定時無做用] 默認’None’,即 Z 的首元素是左下角點。可選’upper’/’lower’/’image’。若是設爲’image’,rc值中的image.origin會被使用。

  • extent:[當 X,Y 指定時無做用] 以四元元組 (x0, x1, y0, y1) 的方式傳值。若是 origin 非 None,它給出圖像的邊界;若是 origin 是 None,則 (x0, y0) 表示 Z[0,0] 的位置,(x1, y1) 表示 Z[-1, -1] 的位置。

至於命令 Axes.clabel(CS, ...),它設置了 CS 對象中存儲的等高線的高度標記格式,具體參數有:

  • inline:布爾型。是否移除高度標記位置下方的等高線,默認 True。

  • inline_spacing:數字。高度標記兩側到等高線的空距,默認 5 像素。

  • fmt:格式化字串。用於指定高度標記的格式,默認 ‘%1.3f’(小數點左一位右三位)。

  • colors:單個字串或一個字串元組。設定高度標記顏色。

# 本例改編自:http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contour.htmlimport matplotlib.mlab as mlabdelta = 0.025x = np.arange(-3.0, 3.0, delta)y = np.arange(-2.0, 2.0, delta)X, Y = np.meshgrid(x, y)  # 生成網格np.random.seed(0)Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)  # 聯合正態Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)Z = 10.0 * (Z2 - Z1)plt.close("all")f, ax = plt.subplots(1, 2, figsize=(10, 5))ax[0].clabel(ax[0].contour(X, Y, Z, 8), inline=True) ax[0].set_title("Colored contour")# 想要取消負高度虛線,使用:# matplotlib.rcParams['contour.negative_linestyle'] = 'solid'ax[1].clabel(ax[1].contour(X, Y, Z, 6, colors="k"), inline=True)ax[1].set_title("Contour: negative dashed")plt.show()

png

# 另外一個例子,也改編自上例import matplotlib.cm as cmplt.close("all")plt.figure()# 顯示一個圖片到座標軸上im = plt.imshow(Z, interpolation='bilinear', origin='lower',
                cmap=cm.gray, extent=(-3, 3, -2, 2))levels = np.arange(-1.2, 1.6, 0.2)CS = plt.contour(Z, levels,
                 origin='lower',
                 linewidths=2,
                 extent=(-3, 3, -2, 2))# 加粗高度爲 0 的等高線zc = CS.collections[6]plt.setp(zc, linewidth=4)# 每隔一個 level, 標記一次高度plt.clabel(CS, levels[1::2],
           inline=1,
           fmt='%1.1f',
           fontsize=14)# 添加一個顏色條CB = plt.colorbar(CS, shrink=0.8, extend='both')plt.title('Lines with colorbar')# 交換如下兩行的註釋與否,能夠獲得不一樣的色圖#plt.hot()plt.flag()# 能夠再加上另外一個顏色條CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8)# 調整先前顏色條的位置l, b, w, h = plt.gca().get_position().boundsll, bb, ww, hh = CB.ax.get_position().boundsCB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])plt.show()

png

說完 contour,再看一個 contourf 的例子:

# 本例改編自:http://www.labri.fr/perso/nrougier/teaching/matplotlib/#contour-plots# import matplotlib.cm as cmplt.close('all')fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)n = 256X,Y = np.meshgrid(np.linspace(-3,3,n), np.linspace(-3,3,n))Z = f(X, Y)# 只畫出邊界:contourC1 = ax1.contour(X, Y, Z, 8, linewidth=.5)ax1.clabel(C1, inline=1, fontsize=10, fmt='%0.1f')  # 等高線標上數字ax1.axis('scaled')# 只填充顏色:contourfax2.contourf(X, Y, Z, 8, alpha=.75, cmap=cm.gray)ax2.axis('scaled')# 繪製邊界並填充顏色ax3.contour(X, Y, Z, 8, color='k', linewidth=.5)ax3.contourf(X, Y, Z, 8, alpha=.75, cmap='jet')ax3.axis('scaled')plt.show()

png

其中,contourf 的 cmap 參數支持的字串有如下幾種:

cmap_paras = ['autumn', 'bone', 'cool', 'copper', 'flag', 'gray', 'hot', 'hsv', 
              'jet', 'pink', 'prism', 'spring', 'summer', 'winter',
              'nipy_spectral', 'nipy_spectral_r']plt.close('all')fig, axarr = plt.subplots(len(cmap_paras), 1, sharex=True, figsize=(15, 4))X, Y = np.meshgrid(np.linspace(0, 10, 1000), np.linspace(0, 1, 10))Z = X axarr[0].set_title('\'cmap\' Parameter (from low to high) ')for index, cmapstr in enumerate(cmap_paras):
    axarr[index].contourf(X, Y, Z, 40, cmap=cmapstr)  # 分爲40級
    axarr[index].text(10.3, 0.2, cmapstr)
    axarr[index].set_yticklabels([])plt.show()

png

其餘命令

 

填充:Axes.fill_between / fill_betweenx

參數:填充指定區域where,使用插值的精確點而不是原有的數據點interpolate=True。

x = np.linspace(0, 2 * np.pi, 1000)plt.close("all")f, ax = plt.subplots(3, 2, sharex="col", figsize=(12, 8))y1 = np.sin(x)y2 = 1.6 * np.sin(2 * x)ax[0,0].fill_between(x, 0, y1)ax[0,0].set_title("Fill between 0 and y1")ax[1,0].fill_between(x, y1, 1)ax[1,0].set_title("Fill between y1 and 1")ax[2,0].plot(x, y1, x, y2, color="k")ax[2,0].fill_between(x, y1, y2)ax[2,0].set_title("Fille between y1 and y2")ax[0,1].plot(x, y1, x, y2, color="k")ax[0,1].fill_between(x, y1, y2, where = y2>y1, facecolor="lightgreen")ax[0,1].fill_between(x, y1, y2, where = y2<y1, facecolor="lightblue")ax[0,1].set_title("Fill between where")ax[1,1].fill_betweenx(x, 0, 4)ax[1,1].set_title("Fill between 0 and 4")ax[2,1].fill_betweenx(x, y1, y2, alpha=0.6)ax[2,1].set_title("Fill between 0 and y1")plt.show()

png

對數座標軸:Axes.loglog / semilogx / semilogy

x = np.arange(0.01, 20, 0.01)plt.close("all")f, ax = plt.subplots(2, 2, figsize=(14, 6))f.subplots_adjust(hspace=0.3)ax[0,0].semilogy(x, np.exp(x))ax[0,0].set_title("semilogy")ax[0,1].semilogx(x, np.sin(2 * np.pi * x))ax[0,1].set_title("semilogx")ax[1,0].loglog(x, 20*np.exp(x), basex=2)ax[1,0].set_title("loglog base 2 on x-axis")ax[1,1].loglog(x, x, visible=False)ax[1,1].set_title("loglog invisible")plt.show()

png

極座標

x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x ** 2)plt.close('all')fig, ax = plt.subplots(1, 1, subplot_kw=dict(projection='polar'))  # 或者 dict(polar=True)ax.plot(x, y)plt.show()

png

左手座標系

實質是翻轉了 X 座標軸。相似地,Y 座標軸也能夠被翻轉。

x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)plt.close("all")f, ax = plt.subplots()ax.plot(x, y)ax.invert_xaxis()ax.set_title("Inverted X-axis")plt.show()

png

能夠用 xaxis_inverted 來檢測座標軸是否處於翻轉狀態:

ax.xaxis_inverted(), ax.yaxis_inverted()
(True, False)

附:GIF 動態圖保存

 

這是一個很是有趣的功能。GIF 動態圖的繪製與生成不一樣於靜態圖像。主要使用 matplotlib 中的 animation 模塊。

前提工做

在開始繪製動態圖以前,你可能須要一些工做來保證命令正常運行:

  1. 下載並安裝 ImageMagick,好比 Windows 用戶選擇「ImageMagick-x.x.x-0-Q16-x64-dll.exe」版本。其中 Q16 表示顏色的位深度,x.x.x是版本號。請記錄你將它安裝到了何處。安裝成功後,在命令行下輸入「convert」應當會正常調用ImageMagick。

  2. 若是在安裝後仍不能生成 GIF,那可能須要編輯你的 matplotlib 配置文件。你能夠這樣查找你的配置文件路徑:

import matplotlib as mplmpl.matplotlib_fname()
'e:\\python\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'

而後用文本編輯器打開 matplotlibrc,找到被「#」註釋的如下兩行:

#animation.ffmpeg_path: 'ffmpeg'
#animation.convert_path: 'convert'

替換爲(路徑改爲你的 ImageMagick 安裝路徑):

animation.ffmpeg_path: F:\ProgramFiles\ImageMagick-7.0.5-Q16\ffmpeg.exe
animation.convert_path: F:\ProgramFiles\ImageMagick-7.0.5-Q16\convert.exe

例子

至於如何生成 GIF,例子以下。一些要點:

  • 一般須要定義一個 update 函數。

  • 經過 FuncAnimation 函數的 interval 參數,控制每幀停留的時間。

  • 你可使用 set_data(須要傳入一個兩行 n 列的 np.array 對象,或者兩個類 List 對象) 代替 set_ydata / set_xdata

from matplotlib.animation import FuncAnimationx = np.linspace(0, 1, 100)y = np.arange(0.05, 5, 0.05)fig, ax = plt.subplots(figsize=(8,6))# 注意這裏把 plot 的結果保存到一個 Lines 對象# 這個初始幀不會寫入到 GIFframes, = ax.plot(x, x)  def update_gif(k, X=x):
    frames.set_ydata(np.power(X, k))
    ax.set_title("Curve of $y=x^k$ when k={:.2f}".format(k))
    ax.axis([0, 1, 0, 1])
    return frames, anim = FuncAnimation(fig, update_gif, y, interval=0.1*1000)  # 依次傳入y並更新幀# 如下是保存爲 gif# gif_path = os.path.join(os.getcwd(), "{0}_files".format("Py3-matplotlib"))# if not os.path.exists(gif_path):#     os.makedirs(gif_path)                 # anim.save(os.path.join(gif_path, "matplotlib-eg.gif"), dpi=100, writer='imagemagick')

因爲不能直接 plt.show(不然會把每一幀輸出爲單獨的圖片),這裏我用 Markdown 的語法來嵌入這個 GIF:

png

若是你以爲 matplotlib + ImageMagick 的操做仍不能知足一些複雜的 GIF 要求,我推薦使用第三方的、帶有圖形界面的 GIF 製做軟件,例如 Ulead Gif Animator.

相關文章
相關標籤/搜索