matplotlib简介
matplotlib是python中用于绘制2D图像,用于科学计算绘图
基本绘图函数说明和例子
-
barh(bottom, width, height=0.8, left=None, **kwargs)
- 绘制矩形的边界为:left,left+width,bottom,bottom+height
- 参数:
- bottom:标量或数组,是条形图的y轴
- width:条形图的每一个条形的宽
- height:条形的高度,标量序列,默认是0.8
- left:条形的左边的边界,标量序列,一般是分类的类别
- **kwargs:关键字参数,可以指定图的格式,颜色等等
- color:标量或者数组,条形的颜色
- edgecolor:边界的颜色、
- linewidth:线宽,0就是不画边界
- tick_label:string或者数组,默认是None,刻度的文
- xerr:标量或者数组,默认是None,如果不是None那么会画出误差线
- yerr:类似与xerr
- align:{‘center’,‘edge’},如果是edge那么垂直条形图条形会在刻度的左边界,水平条形图会对齐底对齐
- log:默认是False,轴长度按照log来
- 例子:
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) /指明刻度对应的标签 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)
- 绘制散点图
- 参数
- x,y:array-like
- s:点的大小,默认rcParams['lines.markersize']**2
- c:color 序列,当是序列的时候,利用cmap,可以是RGB
- marker:标记格式,默认'o'
- cmap:默认None,如果color序列是floa数组的话就调用Colormap,None:rcimage.cmap
- norm:标准化color序列,当且仅当color是float数组
- 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) #标记的大小 plt.scatter(x,y,c=color,s=scale,alpha=0.5,edgecolor='none',label=color) ax.legend() #添加图例 ax.grid(True) #打开网格 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)
- 绘制箱线图,查看数据分布情况和判断数据是否分布对称
- 参数
- x:输入数据,数组或者向量序列
- notch:bool,默认是False,如果是True,那么就会生成带有缺口的箱线图,反映中位数的置信区间
- sym:flier 点,如果是空字符串的话,那么不会显示flier,如果是None,那么默认flier是‘b+’,如果想显示更多flier的格式那么要使用flierprops关键字参数,flier:离群点
- vert:bool 默认True;如果是False,那么箱线图是水平,True就是垂直
- whis:float,String,sequence,默认是1.5;确定正常数据的范围(如果是序列),string=‘range’那么强迫图覆盖最大值到最小;如果是float的话,那么边界点是Q3+whis*(Q3-Q1)
- bootstrap:int
- manage_xticks:bool 默认是True;当是True的话,自动调整标签和x轴范围
- meanline:bool 默认False,如果是True,把均值也画出来
- 例子:
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)
- 步长积累图
- 参数
- x:数组,1-D,一般递增
- y:数组,1-D,一般递增
- where:{'pre','post','mid'}
pre:默认,x[i]到x[i+1]之间有水平y[i+1]
post:间隔有水平y[i]
mid:那么y对应的点出现在间隔的中间
- 例子:
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的格式,标记的格式,线条的格式
- 返回(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)
- 绘制饼图,反映部分占总体的比例
- 参数
- x:部分分别占总体的比例,都是百分数只是没有百分号
- explode:默认None,不为空那么长度肯定是len(x),如果其中一个不为0,其他为0说明该部分需要稍微离开总体一点,数值指定离开的比例
- colors:None,或者color序列,序列这颜色会循环填充部分
- labels:各部分的名称
- autopct:string或function或None,作为数值标注或者将数值输出为指定格式
- 例子:
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)
- 绘制直方图
- 参数
- x:输入值,数组或者n维数组序列
- bins:面元个数 integer或者数组或者auto,如果是Integer,那么将会产生bins+1 个面元
数组,那么面元时间可能不相等 - range:面元的范围,如果None,那么就是(x.min(),x.max())
- normed:如果是True,那么绘制频率分布直方图的时候,就会自动高度=频数/len(x)
- cumulative:积累直方图,默认是False,如果是True那么绘制积累直方图
- stacked:默认False,多个数据堆叠在一起,False:多个数据并排
- histtype:{'bar','barstacked','step','stepfilled'}
bar:条形
barstacked:条形堆积图
step:生成一个线图且没有填充
stepfilled:生成一个填充线图
- 例子:
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()