matplotlib庫的常用知識


看看matplotlib是什么?

matplotlib是python上的一個2D繪圖庫,它可以在誇平台上邊出很多高質量的圖像。綜旨就是讓簡單的事變得更簡單,讓復雜的事變得可能。我們可以用matplotlib生成 繪圖、直方圖、功率譜、柱狀圖、誤差圖、散點圖等 。

matplotlib的發明人為John Hunter(1968-2012),很不幸,他已經在癌症治療過程中引起的綜合症中去世。一代偉人有很多貢獻,我們要緬懷他。如果我們從他的貢獻中受益很大的話,請考慮為John Hunter Technology Fellowship 貢獻你的力量。

下面的內容我們是基於matplotlib 版本1.5.3進行學習。

matplotlib在以后的工作與學習中有很大的用處,很有必要系統學習一下。

我的ipthon nootbook 中,當用plt.show()函數顯示出來了圖片,這時分把程序阻塞,然后關了figure之后,就可以繼續運行,但是這時的上面所創建的figure與axes就相當於清除了。

在Ipython中,我們可能輸入函數名加上??得到函數的源碼;

matplotlib實際上為面向對象的繪圖庫,它所繪制的每個元素都有一個對象與之對應的。

figure就是一個圖啦,axes表示圖上的一個畫圖區域啦,一個圖上可以有多個畫圖區域的啦,意思就是說,一個圖上可以有多個子圖啊。

用函數gcf()與gca()分別得到當前的figure與axes。(get current figure, get current axes).

利用sca()函數實現把一個axes對象作為當前的axes,如果你還想知道,如何把fiure對象作為當前的figure呢?直接輸入figure(1)就可以換到figure1了,再說了,axes對象為figure對象的一個屬性,當切換了axes,figure肯定也切換了啊。如:

plt.figure(1)         #建立figure(1)
plt.figure(2)         #建立figure(2)
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
plt.sca(ax1)         #切換到子圖1
plt.sca(ax2)         #切換到子圖2
plt.figure(1)        #切換到figure(1),它不是重建哦;

 

好啦,現在開始學習:

配置屬性:

因為是面向對象的繪圖庫,我們可以為每個對象配置它們的屬性,應該說有三個方法,一個是通過對象的方法set_屬性名()函數,二是通過對象的set()函數,三是通過pylot模塊提供的setp()函數:

plt.figure()
line = plt.plot(range(5))[0]  #plot函數返回的是一個列表,因為可以同時畫多條線的哦;
line.set_color('r')
line.set_linewidth(2.0)
plt.show()
#————————————  或者  ————————————
plt.figure() line = plt.plot(range(5))[0] #plot函數返回的是一個列表,因為可以同時畫多條線的哦; 
line.set(color = 'g',linewidth = 2.0)
 plt.show() 
#———————————— 或者 ————————————
plt.figure()
lines = plt.plot(range(5),range(5),range(5),range(8,13)) #plot函數返回一個列表;
plt.setp(lines, color = 'g',linewidth = 2.0)         # setp函數可以對多條線進行設置的;
plt.show()

如果想查看呢,怎么辦呢?同樣兩個方法,一個是通過對象的方法get_屬性名()函數,一個是通過pylot模塊提供的getp()函數。

getp()有兩個調用方法,一個是只有要的查看的對象一個參數,一個是要查看的對象現屬性兩個參數;如:

plt.getp(line)
plt.getp(line, 'color'')

 

繪制子圖:

利用subplot()函數可以返回一個axes的對象哦,函數為:subplot(numRows, numCols, plotnum),當這三個參數都小於10時,我們可以把它們寫一起,如下所示: 

#subplot(numRows, numCols, plotnum)
for i, color in enumerate('rgbyck'):    
    plt.subplot(321+i, axis_bgcolor = color)
plt.show()

figure_5

利用subplot_adjust()函數可以對畫的多個子圖進行調整,它一共有left、right, bottom, top, wspace, hspase 六個參數,取 值從0至1。

 

對於上面的很多很多對象,其實都是Artist對象,Artist對象共分為簡單類型和容器類型兩種哦。簡單的類型是標准的繪圖元件,如:line2D, Rectangle, Text, AxesImage等。而容器類型則可以包含許多簡單類型的Artist 對象,如 Figure,Axes,Axis等;

 

舉一個建立簡單Artist對象的過程哈,直接上代碼:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)        # 創建了一個figure對象;

#figure對象的add_axes()可以在其中創建一個axes對象,
# add_axes()的參數為一個形如[left, bottom, width, height]的列表,取值范圍在0與1之間;
ax = fig.add_axes([0.1, 0.5, 0.8, 0.5]) # 我們把它放在了figure圖形的上半部分,對應參數分別為:left, bottom, width, height;
ax.set_xlabel('time')     #用axes對象的set_xlabel函數來設置它的xlabel

line =ax.plot(range(5))[0]  #用axes對象的plot()進行繪圖,它返回一個Line2D的對象;
line.set_color('r')             # 再調用Line2D的對象的set_color函數設置color的屬性;
plt.show()

輸出 為:

QQ截圖20161113181328

 

figure容器: 

在構成圖表的各種Artist對象中,最上層的Artist對象是Figure。我們可以調用add_subplot()與add_axes()方法向圖表中添加子圖,它們分加到figure的axes的屬性列表中。add_subplot()與add_axes()返回新創建的axes對象,分別為axesSuubplot與axes, axesSuubplot為 axes的派生類。另外,可以通過delaxes()方法來刪除哦;

figure對象可以有自己的簡單的artist對象。

下面列出Figure對象中包含的其他Artist對象的屬性:

axes: Axes對象列表;

patch:作為背景的Rectangle對象;

images:FigureImage對象列表,用於顯示圖像;

legends:Legend 對象列表,用於顯示圖示;

lines: Line2D對象列表;

patches: Patch對象列表;

texts:Text 對象列表,用於顯示文字;

axes容器:

它是整個matplotlib的核心,它包含了組成圖表的眾多的artist對象。並且有很多方法。我們常用的Line2D啦,Xaxis,YAxis等都是它的性哦;可以通過這個對象的屬性來設置坐標軸的label啦,范圍啦等之類的。干脆直接用plt.getp()查看它的屬性,然后通過set_屬性名()函數來設置就好啦。

axis容器:

axis容器包括了坐標軸上的刻度線、刻度標簽等、坐標網絡等內容。

對於坐標軸上的刻度相關的知識,它是這么分的:首先是major_ticks()和minor_ticks(), 然后呢,每個刻度又包括刻度線(ticklines)、刻度標簽(ticklabels)、刻度位置(ticklocs)。本來呢,axis應該刻度,然后呢,刻度再包含那三個,但是呢,為了方便,axis就都包含了。其實也是有點交叉吧。上面的axes也會交叉包含它所包含對象的對象的。

看個例子:

plt.plot([1,2,3],[4,5,6])
axis = plt.gca().xaxis        
axis.get_ticklocs()       #得到刻度位置;
axis.get_ticklabels()   #得到刻度標簽;
axis.get_ticklines()   # 得到刻度線;
axis.get_ticklines(minor = True)   #得到次刻度線; 舉個例子:就像我們的尺子上的厘米的為主刻度線,毫米的為次刻度線;
for label in axis.get_ticklabels():  
    label.set_color('red')        #設置每個刻度標簽的顏色;
    label.set_rotation(45)    #旋轉45度;
    label.set_fontsize(16)     #設置字體大小;
for line in axis.get_ticklines():
    line.set_color('green')          
    line.set_markersize(15)      #設置刻度線的長短;
    line.set_markeredgewidth(3)      #設置線的粗細
plt.show()
figure_1

 

最后說一點哦:

pyplot函數提供了兩個繪制文字的函數:text()和figtext()。它們分別調用了當前的Axes對象與當前的Figure對象的text()方法進行繪制文字。text()默認在數字坐標系(就是axes在的坐標系,用坐標軸的數字來表示坐標)中畫, figtext()默認在圖表坐標系(就是figure在圖表中啦,坐標范圍從0 到 1 )中畫,我們可能通過trransform參數進行坐標系的轉換。反正吧,matplotlib中一共有四種坐標系,並且可以轉換的哦,提一下哈。

簡單的調用:

plt.text(1, 1, 
'
hello,world', color = 'bule')   #還可以寫更多參數的;
plt.figtexe(0.1, 0.8 ,"i am in figure', color = 'green')

 

 

上面說了一大堆了,現在說幾個常用的畫圖函數吧:

那就從畫簡單的圖開始嘍:

 

plot(*args, *kwargs)函數,它可以畫出很簡單線圖,基本用法:

plot(x, y)        # 畫出橫軸為x與縱軸為y的圖,使用默認的線形與顏色;
plot(x, y, 'bo')  # 用藍色,且點的標記用小圓,下面會解釋哦
plot(y)           # 縱軸用y ,橫軸用y的每個元素的坐標,即0,1,2……
plot(y, 'r+')     #
 
#如果其中x或y 為2D的,則會用它的相應的每列來表示哦,是每列哦,是每列哦,是每列哦,(重要的事情說三遍)
 
plot(x1, y1, 'g^', x2, y2, 'g-') 
#看到了嗎,我們可以使用多對的x, y, format 對當作變量的哦,把它們畫一個圖里;

對於參數中,常用的format:線的顏色、線的形狀、點的標記形狀,我們用這三個的時候經常用縮寫,它們之間的順序怎么都可以哦,

如它倆一個意思:'r+--'、'+--r'。如果我們不想縮寫的話,可以分別寫成如: color='green', linestyle='dashed', marker='o'。

線的形狀:

'-'    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

線的顏色:

‘b’    blue
‘g’    green
‘r’    red
‘c’    cyan
‘m’    magenta
‘y’    yellow
‘k’    black
‘w’    white

常見線的屬性有:color,labor,linewidth,linestyle,maker,等,具體要看全的話,見:http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D

看一個例子:

import matplotlib.pyplot as plt
import numpy as np  

plt.figure(1) #調用figure函數創建figure(1)對象,可以省略,這樣那plot時,它就自動建一個啦;

t = np.arange(0.0, 2.0, 0.1)
s = np.sin(2*np.pi*t)
plt.plot(t, s, 'r--o', label = 'sinx')

plt.legend()  #顯示右上角的那個label,即上面的label = 'sinx'
plt.xlabel('time (s)')    #設置x軸的label,pyplot模塊提供了很直接的方法,內部也是調用的上面當然講述的面向對象的方式來設置;
plt.ylabel('voltage (mV)')   #設置y軸的label;
#plt.xlim(-1,3)      #可以自己設置x軸的坐標的范圍哦;
#plt.ylim(-1.5,1.5)   #同上;
plt.title('About as simple as it gets, folks')  
plt.grid(True)   #顯示網格;

plt.show()   #顯示出figure;
figure_1

 

 

函數subplots()

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, **fig_kw)
#作用:創建一個已有subplots的figures;
參數:
      *nrows* : int  ,指創建的sublots的行數,默認為1.

      *ncols* : int  ,指創建的sublots的列數,默認為1.

     *sharex* : 為一個string或bool類型;
        當為Ture時,所有的subpots將要共享x軸,如果它們是上下的關系的話,上面的圖的刻度label就沒有,只有下面那個圖的.
        If a string must be one of "row", "col", "all", or "none".
        "all" has the same effect as *True*, "none" has the same effect
        as *False*.
        If "row", each subplot row will share a X axis.
        If "col", each subplot column will share a X axis and the x tick
        labels on all but the last row will have visible set to *False*.

      *sharey* : 同上

      *squeeze* : bool  它是用來控制返回值的,根據返回的axis的結果決定要不要把沒有的維度進行壓縮一下.
           當為Ture時,如果返回的axis只有一個,則表示成標量,如果有一行或一列,則表示為一維數組,如果多行多列,則表示為2D數組;
           當為False時,不管多少個返回的axis,都以二維數組的方式返回;
      *subplot_kw* : dict
        Dict with keywords passed to the
        :meth:`~matplotlib.figure.Figure.add_subplot` call used to
        create each subplots.

      *fig_kw* : dict
        Dict with keywords passed to the :func:`figure` call.  Note that all
        keywords not recognized above will be automatically included here.

  返回值

  有兩個fig和 axt(它是元組的方式哦)

      - *fig* is the :class:`matplotlib.figure.Figure` object

      - *ax* can be either a single axis object or an array of axis
        objects if more than one subplot was created.  The dimensions
        of the resulting array can be controlled with the squeeze
        keyword, see above.

看個例子:

import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
plt.show()

figure_1

 

 

 

函數:twinx()或twiny()

它的作用就是:共享x軸,再給一個axis.看看牛逼的英文怎么說的:

create a twin of Axes for generating a plot with a sharex
        x-axis but independent y axis.  The y-axis of self will have
        ticks on left and the returned axes will have ticks on the
        right.

函數:twiny():和上面一樣,不同之處在於,它共享y軸。

import matplotlib.pyplot as plt
fig = plt.figure(1)
ax1 =plt.subplot(111)
ax2 = ax1.twinx()
ax1.plot(np.arange(1,5),'g--')
ax1.set_ylabel('ax1',color = 'r')
ax2.plot(np.arange(7,10),'r-')
ax2.set_ylabel('ax2',color = 'g')
plt.show()

figure_1

 

 

 

再寫一個關於subplot的一個demo.

直接上代碼:

"""
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt


x1 = np.linspace(0.0, 5.0)   #生成一個一維的array,linspace(起始點,結束點,點數(默認為50))
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 2, 1)      #表示在subplot為2*1的樣式,並在第一個子圖上畫出;
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 2, 2)      #  我們在第二個子圖上加個空圖哈,去理解它的圖的排序(即注意第二個子圖的位置
                                    #  為第一行第二列)是按行優先的,這個正好和matlab里相反哦;

plt.subplot(2, 2, 4)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

figure_2

 

 

 

再來瞧瞧直方圖。

#函數hist,不過有點長哦,很多參數可以省略的哦;
n, bins, patches = hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)

參數的意義:

x : (n,) array or sequence of (n,) arrays,表示:就是輸入的數據啦,可以為一個序列數,也可以多組;

bins : integer or array_like, 表示:控制分的塊數,要分的塊數為bins,默認為10;

range : tuple or None, optional, 表示畫圖的范圍大小 ;詳細你們看英語哈;

The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()). Range has no effect if bins is a sequence.

If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.

Default is None

normed : boolean, optional, 意義就是說,返回的第一個n(后面解釋它的意義)吧,把它們正則化它,讓bins的值 的和為1,這樣差不多相當於概率分布似的了;

If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., n/(len(x)`dbin), i.e., the integral of the histogram will sum to 1. If stacked is also True, the sum of the histograms is normalized to 1.

Default is False

weights : (n, ) array_like or None, optional 啥意義啊,不知道 哦

An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If normed is True, the weights are normalized, so that the integral of the density over the range remains 1.

Default is None

cumulative : boolean, optional     ,就是每一列都把之前的加起來,可能這么說不嚴謹哦,不過就是那個意思;

If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints. If normed is also True then the histogram is normalized such that the last bin equals 1. If cumulative evaluates to less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if normed is also True, then the histogram is normalized such that the first bin equals 1.

Default is Fal

bottom : array_like, scalar, or None,下面的每個bin的基線,表示bin的值都從這個基線上往上加;

Location of the bottom baseline of each bin. If a scalar, the base line for each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults t

Default is None

histtype : {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, optional, 表明了畫出的bar的形狀;

The type of histogram to draw.

‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are aranged side by side.

‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.

‘step’ generates a lineplot that is by default unfilled.

‘stepfilled’ generates a lineplot that is by default filled.

Default is ‘bar’

align : {‘left’, ‘mid’, ‘right’}, optional 它決定了你畫的bar是以什么為中心的。你看看哈,畫圖時,每個bin的邊界已經分好了,align就決定了你畫每一個bar時,要依左邊界為中心呢,還是右邊界,還是中間呢?當然默認為中間了,這樣才准確的

Controls how the histogram is plotted. 

  • ‘left’: bars are centered on the left bin edges.
  • ‘mid’: bars are centered between the bin edges.
  • ‘right’: bars are centered on the right bin edges.

Default is ‘mid’

orientation : {‘horizontal’, ‘vertical’}, optional:指的方向,分為水平與垂直兩個方向。

If ‘horizontal’, barh will be used for bar-type histograms and the bottom kwarg will be the left edges.

rwidth : scalar or None, optional ,控制你要畫的bar 的寬度哦;

The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.

Ignored if histtype is ‘step’ or ‘stepfilled’.

Default is None

log : boolean, optional 

If True, the histogram axis will be set to a log scale. If log is True and x is a 1D array, empty bins will be filtered out and only the non-empty (n, bins, patches) will be returned.

Default is False

color : color or array_like of colors or None, optional   表示bar的顏色;

Color spec or sequence of color specs, one per dataset. Default (None) uses the standard line color sequence.

Default is None

label : string or None, optional  這個不錯,可以給圖上畫的加個標簽,要加上這么一句哦;plt.legend() 作用為顯示出來;

String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that the legend command will work as expected.

default is None

stacked : boolean, optional   作用就是當多個輸入的時候,要不要把它們luo 起來;

If True, multiple data are stacked on top of each other If False multiple data are aranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’

Default is False

 

 

輸出參數:

n : array or list of arrays     每一個 bin的值;

The values of the histogram bins. See normed and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence arrays [data1, data2,..], then this is a list of arrays with the values of the histograms for each of the arrays in the same order.

bins : array  :返回bin的邊界值,長度為bin的數目 + 1.

The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.

patches : list or list of lists

Silent list of individual patches used to create the histogram or list of such list if multiple input datasets.

來,看個圖:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt


# example data
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)      #np.random.randn(n)函數的作用為生成n個標准的正態分布的數;

num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, bins = num_bins, normed=1, color='b', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma) # normpdf(x,mu,sigma):返回參數為μ和σ的正態分布密度函數在x處的值
                                                            # (其中參數mu是μ,參數sigma是σ)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)   #把畫的圖從左邊0.15(整個為1)處開始, 要不把y軸的label顯示不出來 ,可以設為0試試.
                                                 # 另外,其實不加也沒事;
plt.show()

figure_3

 

 

再來看一個餅形圖:

函數pie()如下所示,它畫出數組x表示的餅形圖,每一份的比例為x/sum(x);如果sum(x)的和小於1,那么,直接用x的值當作比例哦,不會去標准化它。默認的塊是逆時針來的,從x軸開始。

pie(x, explode=None, labels=None,
    colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'),
    autopct=None, pctdistance=0.6, shadow=False,
    labeldistance=1.1, startangle=None, radius=None,
    counterclock=True, wedgeprops=None, textprops=None,
    center = (0, 0), frame = False, hold = None, data = None )

 

 

參數的意義:

explode: [ None | len(x) sequence ] 為None或着長度為len(x)的數的序列,表明每一塊中心與圓心的位移,基本都是小數哦,意思就是讓每一塊分開一定距離,這樣好看;

If not None, is a len(x) array which specifies the fraction of the radius with which to offset each wedge.

colors: [ None | color sequence ]  表示每一塊的顏色;

A sequence of matplotlib color args through which the pie chart will cycle.

labels: [ None | len(x) sequence of strings ]  表示每一塊的標簽;

A sequence of strings providing the labels for each wedge

autopct: [ None | format string | format function ] ,用於標記它們的值(大小為x/sum(x)*100);,可以為一個format string,或function。如format string, %d(整數),%1.1f(保留一位的小數)等

If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt%pct. If it is a function, it will be called.

pctdistance: scalar ,用於控制上面的那個autopct生成的顯示的值 的位置,默認離每一塊的中心0.6的比例處;

The ratio between the center of each pie slice and the start of the text generated by autopct. Ignored if autopct is None; default is 0.6.

labeldistance: scalar 控制那個label的位置,它代表了徑向的相對距離哦;

The radial distance at which the pie labels are drawn

shadow: [ False | True ] 要不要畫個陰影呢?它決定!!!

Draw a shadow beneath the pie.

startangle: [ None | Offset angle ]  開始的位置偏移的角度;

If not None, rotates the start of the pie chart by angle degrees counterclockwise from the x-axis.

radius: [ None | scalar ] The radius of the pie, if radius is None it will be set to 1. 直徑的大小;

counterclock: [ False | True ]   逆時針還是順時針呢;

Specify fractions direction, clockwise or counterclockwise. 

wedgeprops: [ None | dict of key value pairs ]  用字典屬性指定了塊的一些屬性;

Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = { ‘linewidth’ : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default clip_on=False.

textprops: [ None | dict of key value pairs ]   用字典屬性指定了text的屬性;

Dict of arguments to pass to the text objects.

center: [ (0,0) | sequence of 2 scalars ] Center position of the chart. 它的中心位置啦;

frame: [ False | True ] 它決定了你要不要顯示坐標軸哦;

Plot axes frame with the chart.

另外還有兩個參數:

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments are replaced by data[<arg>]:

All arguments with the following names: ‘x’, ‘labels’, ‘colors’, ‘explode’.
Additional kwargs: hold = [True|False] overrides default hold state

返回值:

If autopct is None, return the tuple (patches, texts):

patches is a sequence of matplotlib.patches.Wedge instances
texts is a list of the label matplotlib.text.Text instances.
If autopct is not None, return the tuple (patches, texts, autotexts), where patches and texts are as above, and autotexts is a list of Text instances for the numeric labels.

說了一大堆了,來舉個例子啦:

import matplotlib.pyplot as plt

# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'      
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']   #這個顏色有點牛逼;
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')  #讓坐標的橫軸與縱軸相等,這樣圓才是圓的哦,目的好看啊.
plt.show()

figure_4

 

 

來,再來學習畫3D圖形啦。mplot3d rutorial

mpl_toolkits.mplot3d模塊在matplotlib基礎上提供了三維繪圖的功能。由於它使用matplotlib的二維繪圖功能來實現三維的圖形的繪制工作,所以呢,速度是有限滴,不過呢,對於我們平時畫個小圖啦,是綽綽有余的。現在開始學習啦!

首先我們開始的話,就要創建一個Axes3D對象:現在吧,我們是基於version1.5.1來說的哦:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

 

畫三維曲線圖:

Axes3D.plot(self, xs, ys, *args, **kwargs):

 

 

         =====  ================================================
        Argument    Description
        ==========  ================================================
        *xs*, *ys*  X, y coordinates of vertices

        *zs*        z value(s), either one for all points or one for
                    each point.
        *zdir*      Which direction to use as z ('x', 'y' or 'z')
                    when plotting a 2D set.
     ==========  ================================================
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt  #ddf

mpl.rcParams['legend.fontsize'] = 10        # 設置圖示的字體大小;

fig = plt.figure()
ax = fig.gca(projection='3d')  #它表示得到一個3D的axes, 
                               #也可以用代碼: ax = fig.add_subplot(111, projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(0, 4, 100)
r = z
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')           #直接把x, y, z 三者對應的坐標的點傳進去了呀
ax.legend()               #顯示圖示;
 
plt.show()

figure_1

 

surface plots:

Axes3D.plot_surface(X, Y, Z, *args, **kwargs)Create a surface plot.

By default it will be colored in shades of a solid color, but it also supports color mapping by supplying the cmap argument.

The rstride and cstride kwargs set the stride used to sample the input data to generate the graph. If 1k by 1k arrays are passed in the default values for the strides will result in a 100x100 grid being plotted.

其中一參數:

X, Y, Z    Data values as 2D arrays  #傳入的變量;
rstride    Array row stride (step size), defaults to 10  #選擇網絡中的點的步長,步長越小圖越好。
cstride    Array column stride (step size), defaults to 10
color    Color of the surface patches   
cmap    A colormap for the surface patches.
facecolors    Face colors for the individual patches
norm    An instance of Normalize to map values to colors
vmin    Minimum value to map
vmax    Maximum value to map
shade    Whether to shade the facecolors

具體參數管什么用哈,我們就看看例子怎么用,我也沒有深入研究:

例子1:

aafrom mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm      #里面有很多顏色映射表;
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)             #創建X——Y平面表格;
R = np.sqrt(X**2 + Y**2)              #計算每點的高度;
Z = np.cos(R)                     
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01) 

ax.zaxis.set_major_locator(LinearLocator(10))    #設置z軸的坐標為線性的,且有10個坐標標記啦;
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))     #應該設置了這個z軸坐標的顯示格式啦;
fig.colorbar(surf, shrink=.5, aspect=5)           #設置那個顏色帶的大小;

plt.show()

輸出為:

figure_1

 

例子2:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
    for x in range(xlen):
        colors[x, y] = colortuple[(x + y) % len(colortuple)]

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
                       linewidth=0, antialiased=False)

ax.set_zlim3d(-1, 1)
ax.w_zaxis.set_major_locator(LinearLocator(6))

plt.show()

輸出 :

figure_1

Polygon plots:

Axes3D.add_collection3d(col, zs=0, zdir='z')Add a 3D collection object to the plot.

2D collection types are converted to a 3D version by modifying the object and adding z coordinate information.

Supported are:
  • PolyCollection
  • LineColleciton
  • PatchCollection
舉個例子:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib.colors import colorConverter
import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure()
ax = fig.gca(projection='3d')


def cc(arg):              #它的作用就是改改顏色啦,把顏色的A值 改為0.5,(RGBA是什么看百度,它代表了4個值,然后呢,函數把傳入的顏色的lapha值變為0.5)
    return colorConverter.to_rgba(arg, alpha=0.5)

xs = np.arange(0, 10, 0.4)
verts = []
zs = [0.0, 1.0, 2.0, 3.0]
for z in zs:                                          #生成x值、y值對。
    ys = np.random.rand(len(xs))           #產生在0-1之間均勻分布的一定個數的隨機數;
    ys[0], ys[-1] = 0, 0               
    verts.append(list(zip(xs, ys)))                #函數zip()的作用就是把傳放的xs, ys一維數組變為[(xs0, ys0),  (xs1, ys1), (xs1, ys1),   ……]

poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'),
                                         cc('y')])
poly.set_alpha(0.7)                  #設置透明度;
ax.add_collection3d(poly, zs=zs, zdir='y')           #把z軸方向變為y軸方向;

ax.set_xlabel('X')
ax.set_xlim3d(0, 10)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 4)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)

plt.show()

輸出:

figure_1

 

關於matplotlib里的簡單圖像的imread()與imshow()函數:

plt.imshow()函數,可以從圖像文件讀入數據,得到一個表示圖像的Numpy數組。它的第一個參數是文件名或文件對象,第二個參數format指定圖像類型,如果省略,就由文件的擴展名決定圖像的類型。對於灰度圖像,它返回一個形狀為(M,N)的數組,對於彩色圖像,返形狀為(M,N,C)的數組。M,N表示圖像的高度與寬度,C為3或4,表示圖像的通道數。

import matplotlib.pyplot as plt
import numpy as np
img = plt.imread('lena.jpg')

img.shape
#輸出為:
(256,256, 3)

img.dtype
#輸出為:
dtype('uint8')plt.imshow(img) 
plt.colorbar()    # 顯示顏色映射表;

plt.show()

figure_1

如果在三維數組中的元素類型為浮點類型的話,那么元素的聚會范圍為0.0至1.0,與顏色值的0至255對應 。 超出了這個范圍,可能出現顏色異常的像素。如果imshow()的參數為二維數組的話,就使用顏色映射表決定每個像素的顏色。默認的顏色映射將最小值映射為藍色,最大值電映射為紅色。

# 接上面的繼續來:

fig = plt.figure(1)
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
plt.sca(ax1)
plt.imshow(img[:,:,0])
#plt.axis('off')  
plt.colorbar()
plt.sca(ax2)
plt.imshow(img[:,:,1])
#plt.axis('off') 
plt.colorbar()
plt.sca(ax3)
plt.imshow(img[:,:,2])
#plt.axis('off') 
plt.colorbar()
plt.show()

figure_1

通過imshow()的cmap參數可以修改顯示圖像時所采用的顏色映射表。顏色映射表是一個 ColorMap對象,matplotlib中已經預先定義了很多顏色映射表。可以通過下面的語句得到:

import matplotlib.cm as cm
cm._cmapnames
輸出:
['Spectral',
 'copper',
 'RdYlGn',
 'Set2',
 'summer',
 'spring',
 'gist_ncar',
 'terrain',
 'OrRd',
 'RdBu',
 'autumn',
 'gist_earth',
 'Set1',
 'PuBu',
 'Set3',
 'brg',
 'gnuplot2',
 'gist_rainbow',
 'pink',
 'binary',
 'winter',
 'jet',
 'BuPu',
 'Dark2',
 'prism',
 'Oranges',
 'gist_yarg',
 'BuGn',
 'hot',
 'PiYG',
 'YlOrBr',
 'PRGn',
 'Reds',
 'spectral',
 'bwr',
 'RdPu',
 'cubehelix',
 'Greens',
 'rainbow',
 'Accent',
 'gist_heat',
 'YlGnBu',
 'RdYlBu',
 'Paired',
 'flag',
 'hsv',
 'BrBG',
 'seismic',
 'Blues',
 'Purples',
 'cool',
 'Pastel2',
 'gray',
 'coolwarm',
 'Pastel1',
 'gist_stern',
 'gnuplot',
 'GnBu',
 'YlGn',
 'Greys',
 'RdGy',
 'ocean',
 'YlOrRd',
 'PuOr',
 'PuRd',
 'gist_gray',
 'CMRmap',
 'PuBuGn',
 'nipy_spectral',
 'afmhot',
 'bone']

 

 

 

 

參考:http://matplotlib.org/index.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM