matplotlib簡(jiǎn)介
matplotlib是python中用于繪制2D圖像枯途,用于科學(xué)計(jì)算繪圖
基本繪圖函數(shù)說(shuō)明和例子
-
barh(bottom, width, height=0.8, left=None, **kwargs)
- 繪制矩形的邊界為:left,left+width,bottom,bottom+height
- 參數(shù):
- bottom:標(biāo)量或數(shù)組,是條形圖的y軸
- width:條形圖的每一個(gè)條形的寬
- height:條形的高度逊彭,標(biāo)量序列,默認(rèn)是0.8
- left:條形的左邊的邊界识虚,標(biāo)量序列檐束,一般是分類的類別
- **kwargs:關(guān)鍵字參數(shù),可以指定圖的格式般码,顏色等等
- color:標(biāo)量或者數(shù)組搔驼,條形的顏色
- edgecolor:邊界的顏色、
- linewidth:線寬侈询,0就是不畫(huà)邊界
- tick_label:string或者數(shù)組舌涨,默認(rèn)是None,刻度的文
- xerr:標(biāo)量或者數(shù)組扔字,默認(rèn)是None囊嘉,如果不是None那么會(huì)畫(huà)出誤差線
- yerr:類似與xerr
- align:{‘center’,‘edge’}革为,如果是edge那么垂直條形圖條形會(huì)在刻度的左邊界扭粱,水平條形圖會(huì)對(duì)齊底對(duì)齊
- log:默認(rèn)是False,軸長(zhǎng)度按照l(shuí)og來(lái)
- 例子:
import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt plt.rcdefaults() fig, ax = plt.subplots() # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) ax.barh(y_pos, performance, align='center', color='green') ax.set_yticks(y_pos) /指明y軸的刻度 ax.set_yticklabels(people) /指明刻度對(duì)應(yīng)的標(biāo)簽 ax.invert_yaxis() # 按照從上往下讀的順序 ax.set_xlabel('Performance') ax.set_title('How fast do you want to go today?') plt.show()
-
scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, **kwargs)
- 繪制散點(diǎn)圖
- 參數(shù)
- x震檩,y:array-like
- s:點(diǎn)的大小琢蛤,默認(rèn)rcParams['lines.markersize']**2
- c:color 序列,當(dāng)是序列的時(shí)候抛虏,利用cmap博其,可以是RGB
- marker:標(biāo)記格式,默認(rèn)'o'
- cmap:默認(rèn)None迂猴,如果color序列是floa數(shù)組的話就調(diào)用Colormap慕淡,None:rcimage.cmap
- norm:標(biāo)準(zhǔn)化color序列,當(dāng)且僅當(dāng)color是float數(shù)組
- alpha:透明度
- edgecolor:邊界的顏色
- 例子:
import matplotlib.pyplot as plt import numpy.random as random fig,ax=plt.subplots() for color in ['red','green','blue']: n=100 x,y=random.randn(2,n) scale=200.0*random.rand(n) #標(biāo)記的大小 plt.scatter(x,y,c=color,s=scale,alpha=0.5,edgecolor='none',label=color) ax.legend() #添加圖例 ax.grid(True) #打開(kāi)網(wǎng)格 plt.show()
-
箱線圖boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_xticks=True, autorange=False, zorder=None)
- 繪制箱線圖沸毁,查看數(shù)據(jù)分布情況和判斷數(shù)據(jù)是否分布對(duì)稱
- 參數(shù)
- x:輸入數(shù)據(jù)峰髓,數(shù)組或者向量序列
- notch:bool傻寂,默認(rèn)是False,如果是True携兵,那么就會(huì)生成帶有缺口的箱線圖疾掰,反映中位數(shù)的置信區(qū)間
- sym:flier 點(diǎn),如果是空字符串的話徐紧,那么不會(huì)顯示flier个绍,如果是None,那么默認(rèn)flier是‘b+’浪汪,如果想顯示更多flier的格式那么要使用flierprops關(guān)鍵字參數(shù)巴柿,flier:離群點(diǎn)
- vert:bool 默認(rèn)True;如果是False死遭,那么箱線圖是水平广恢,True就是垂直
- whis:float,String呀潭,sequence钉迷,默認(rèn)是1.5;確定正常數(shù)據(jù)的范圍(如果是序列)钠署,string=‘range’那么強(qiáng)迫圖覆蓋最大值到最锌反稀;如果是float的話谐鼎,那么邊界點(diǎn)是Q3+whis*(Q3-Q1)
- bootstrap:int
- manage_xticks:bool 默認(rèn)是True舰蟆;當(dāng)是True的話,自動(dòng)調(diào)整標(biāo)簽和x軸范圍
- meanline:bool 默認(rèn)False狸棍,如果是True身害,把均值也畫(huà)出來(lái)
- 例子:
import matplotlib.pyplot as plt import numpy as np # Random test data np.random.seed(123) all_data = [np.random.normal(0, std, 100) for std in range(1, 4)] fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(9, 4)) # rectangular box plot bplot1 = axes[0].boxplot(all_data, vert=True, # vertical box aligmnent patch_artist=True) # fill with color # notch shape box plot bplot2 = axes[1].boxplot(all_data, notch=True, # notch shape vert=True, # vertical box aligmnent patch_artist=True) # fill with color # fill with colors colors = ['pink', 'lightblue', 'lightgreen'] for bplot in (bplot1, bplot2): for patch, color in zip(bplot['boxes'], colors): patch.set_facecolor(color) # adding horizontal grid lines for ax in axes: ax.yaxis.grid(True) ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') # add x-tick labels plt.setp(axes, xticks=[y+1 for y in range(len(all_data))], xticklabels=['x1', 'x2', 'x3', 'x4']) plt.show()
-
步階圖step(x, y, *args, **kwargs)
- 步長(zhǎng)積累圖
- 參數(shù)
- x:數(shù)組,1-D草戈,一般遞增
- y:數(shù)組塌鸯,1-D,一般遞增
- where:{'pre','post','mid'}
pre:默認(rèn)唐片,x[i]到x[i+1]之間有水平y(tǒng)[i+1]
post:間隔有水平y(tǒng)[i]
mid:那么y對(duì)應(yīng)的點(diǎn)出現(xiàn)在間隔的中間
- 例子:
import numpy as np from numpy import ma import matplotlib.pyplot as plt x = np.arange(1, 7, 0.4) y0 = np.sin(x) y = y0.copy() + 2.5 plt.step(x, y, label='pre (default)') y -= 0.5 plt.step(x, y, where='mid', label='mid') y -= 0.5 plt.step(x, y, where='post', label='post') y = ma.masked_where((y0 > -0.15) & (y0 < 0.15), y - 0.5) plt.step(x, y, label='masked (pre)') plt.legend() plt.xlim(0, 7) plt.ylim(-0.5, 4) plt.show()
-
pyplot.stem(args,*kwargs)
- 繪制莖葉圖
- x:array-like
- y:array-like
- 可以利用linefmt,markerfmt,basefmt:指定baseline的格式丙猬,標(biāo)記的格式,線條的格式
- 返回(markerline,stemline,baseline)
- 例子:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.1, 2*np.pi, 10) markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.') plt.setp(baseline, 'color', 'r', 'linewidth', 2) plt.show()
-
pyplot.pie(x, explode=None, labels=None, colors=None, 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)
- 繪制餅圖费韭,反映部分占總體的比例
- 參數(shù)
- x:部分分別占總體的比例茧球,都是百分?jǐn)?shù)只是沒(méi)有百分號(hào)
- explode:默認(rèn)None,不為空那么長(zhǎng)度肯定是len(x)揽思,如果其中一個(gè)不為0袜腥,其他為0說(shuō)明該部分需要稍微離開(kāi)總體一點(diǎn)见擦,數(shù)值指定離開(kāi)的比例
- colors:None钉汗,或者color序列羹令,序列這顏色會(huì)循環(huán)填充部分
- labels:各部分的名稱
- autopct:string或function或None,作為數(shù)值標(biāo)注或者將數(shù)值輸出為指定格式
- 例子:
import matplotlib.pyplot as plt # Pie chart, where the slices will be ordered and plotted counter-clockwise: labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()
-
pyplot.hist(x, bins=None, 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, **kwargs)
- 繪制直方圖
- 參數(shù)
- x:輸入值损痰,數(shù)組或者n維數(shù)組序列
- bins:面元個(gè)數(shù) integer或者數(shù)組或者auto福侈,如果是Integer,那么將會(huì)產(chǎn)生bins+1 個(gè)面元
數(shù)組卢未,那么面元時(shí)間可能不相等 - range:面元的范圍肪凛,如果None,那么就是(x.min(),x.max())
- normed:如果是True辽社,那么繪制頻率分布直方圖的時(shí)候伟墙,就會(huì)自動(dòng)高度=頻數(shù)/len(x)
- cumulative:積累直方圖,默認(rèn)是False滴铅,如果是True那么繪制積累直方圖
- stacked:默認(rèn)False戳葵,多個(gè)數(shù)據(jù)堆疊在一起,F(xiàn)alse:多個(gè)數(shù)據(jù)并排
- histtype:{'bar','barstacked','step','stepfilled'}
bar:條形
barstacked:條形堆積圖
step:生成一個(gè)線圖且沒(méi)有填充
stepfilled:生成一個(gè)填充線圖
- 例子:
import numpy as np import matplotlib.pyplot as plt np.random.seed(0) mu = 200 sigma = 25 x = np.random.normal(mu, sigma, size=100) fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(8, 4)) ax0.hist(x, 20, normed=1, histtype='stepfilled', facecolor='g', alpha=0.75) ax0.set_title('stepfilled') # Create a histogram by providing the bin edges (unequally spaced). bins = [100, 150, 180, 195, 205, 220, 250, 300] ax1.hist(x, bins, normed=1, histtype='bar', rwidth=0.8) ax1.set_title('unequal bins') fig.tight_layout() plt.show()