Python第三方库——Matplotlib库

    xiaoxiao2021-03-25  283

    pyplot模块figure模块axes模块gridspec模块实践 绘制confusion matrix 问题更多阅读

    import matplotlib.pyplot as plt

    pyplot模块

    plt.ion():打开交互模式

    plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs) 参数: num:整数或者字符串,默认值是None。figure对象的id。如果没有指定num,那么会创建新的figure,id(也就是数量)会递增,这个id存在figure对象的成员变量number中;如果指定了num值,那么检查id为num的figure是否存在,存在的话直接返回,否则创建id为num的figure对象,并且如果num是字符串类型,窗口的标题会设置成num。 fsize:整数元组,默认值是None。表示宽、高的inches数。 dpi:整数,默认值为None。表示figure的分辨率 facecolor:背景颜色 edgecolor:边缘颜色 返回: figure:Figure对象

    ax = plt.subplot(*args, **kwargs): 关键字参数: facecolor:subplot的背景颜色 projection: 返回:

    subplot(nrows, nclos, plot_number)#将figure划分成nrows行ncols列个子坐标。plot_number用来返回指定的subplot,从1开始,先横向后纵向 #当行、列和plot_number都小于10的时候,可以用下面的简单的调用形式来指定行列数及plot_number subplot(211)

                例子:

    import matplotlib.pyplot as plt # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) # now create a subplot which represents the top plot of a grid with 2 rows and 1 column. #Since this subplot will overlap the # first, the plot (and its axes) previously created, will be removed plt.subplot(211) plt.plot(range(12)) plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background

    fig, ax = plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): 创建一个figure和多个子图。 参数: nrows,ncols:int类型,默认值为1,表示子图窗格数 sharex,sharey:bool或者{‘none’, ‘all’, ‘row’, ‘col’},默认值为False。控制x、y坐标轴的属性共享。当为True或者’all’表示在所有子图中共享坐标轴;False或者’none’表示每个子图的坐标轴是独立的;’row’表示每个子图行会共享坐标轴;’col’表示每个子图列会共享坐标轴。 squeeze:bool,默认值为True。 subplot_kw:dict。保存的是传给add_subplot()的参数 gridspec_kw:dict。 fig_kw:dict。 返回: fig:matplotlib.figure.Figure对象,fig可以用于修改图片级别的属性。 ax:Axes对象或者Axes对象的数据。

    plt.axis(*v, **kwargs):获得或者设置坐标属性的便捷方法

    plt.axis():返回当前坐标的范围[xmin, xmax, ymin, ymax] plt.axis(v):设置x和y坐标的最大最下值,v=[xmin, xmax, ymin, ymax] plt.axis('off'):去掉坐标轴和标签 plt.axis('equal'): plt.axis('scaled'): plt.axis('tight'):修改x、y坐标的范围让所有的数据显示出来 plt.axis('image'):

    plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs): 参数: X:array_like或者PIL图像对象,shape为[n,m]或[n,m,3]或[n,m,4]。表示要在当前axes中展示的图片。 cmap:Colormap。 aspect:[‘auto’ | ‘equal’ | ‘scalar’],’auto’表示调整图片的aspect比例使用axes,’equal’表示调整axes适应图片 返回: img:AxesImage类型

    savefig(*args, **kwargs):保存当前figure。 参数: fname:string(文件名)或者文件对象。当fname是文件对象时,需要指定format参数。 bbox_inches:只保存部分figure。如果为’tight’,试着从figure中去掉bbox。

    pause(interval):暂停一段时间。如果是动态figure,GUI事件会在暂停的时候执行;如果没有动态figure,或者是非交互后缀,执行time.sleep(interval)。

    figure模块

    Figure类:所有绘图元素的顶层容器 成员变量:

    axes:Figure对象的axes列表

    成员函数:

    axes模块

    Axes类:包含大多数figure元素:Axis、Tick、Line2D、Text、Polygon等。还可以设置坐标轴。 成员函数:

    ax.set_xticklabels(labels, fontdict=None, minor=False, **kwargs):设置x坐标上每个刻度的标签 参数: labels:字符串序列 返回:

    ax.set_yticklabels([])

    cla():清除当前axes。

    imshow(X, cmap=None):在axes上显示图片 参数: X:array_like或者PIL图片,shape为[n,m], [n,m,3]或者[n,m,4]。 cmap:ColorMap,默认值为None。

    -contour(*args, **kwargs):绘制轮廓

    contour(Z):绘制数组Z的轮廓 contour(X, Y, Z):X、Y指明surface(x,y)坐标 contour(Z, N):至多N个自动选择的levelcontour(Z, V):在序列V指定的值处绘制轮廓线,V必须是递增的 set_axis_off():把axis关闭

    gridspec模块

    import matplotlib.gridspec as gridspec 此模块用于指定subplot在figure的位置。

    类GridSpec:指定subplot的框格 成员函数:

    构造函数GridSpec(nrows, ncols, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None): 参数: nrows:框格的行数 ncols:框格的列数

    gs.update(wspace=0.05, hspace=0.05):更新当前值

    示例:

    import matplotlib.gridspec as gridspec fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect('equal') plt.imshow(sample.reshape(28, 28), cmap='Greys_r')

    实践

    绘制confusion matrix

    import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np def makeconf(conf_arr, model_name): # makes a confusion matrix plot when provided a matrix conf_arr # every row of conf_arr is normalized norm_conf = [] for i in conf_arr: a = 0 tmp_arr = [] a = sum(i, 0) for j in i: tmp_arr.append(float(j)/float(a)) norm_conf.append(tmp_arr) fig = plt.figure() plt.clf() #清除画布 ax = fig.add_subplot(111) #参数的意思是把画布分成1行1列,把图画在第1块(从上到下从左到右数起)。也可以写成 fig.add_subplot(1,1,1) ax.set_aspect(1) #控制纵横比,1:1 res = ax.imshow(np.array(norm_conf), cmap=plt.cm.jet, interpolation='nearest') #根据np array的数组绘制图,第二个参数是配色,有jet、gray width = len(conf_arr) height = len(conf_arr[0]) for x in xrange(width): for y in xrange(height): ax.annotate(str(conf_arr[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center') #在每一块表上数字,第一个参数是要标上的字符串,第二个是坐标 cb = fig.colorbar(res)  #在图的旁边绘制一个bar,展示颜色代表的数值 indexs = '0123456789' plt.xticks(range(width), indexs[:width]) #x, y轴的坐标名 plt.yticks(range(height), indexs[:height]) # you can save the figure here with: # plt.savefig("pathname/image.png") plt.savefig("conf_matrix/{}_confusion_matrix.png".format(model_name)) if __name__=="__main__": y = [1,0,1,1,1,0,0] predicts = [1,1,0,1,0,1,0] conf_matrix = confusion_matrix(y, predicts) print conf_matrix makeconf(conf_matrix, "test")

    问题

    想在绘制的图中显示中文信息,需要修改配置文件:/usr/local/lib/python2.7/dist-packages/matplotlib/mpl-data/matplotlibrc 把font.family和font.sans.seris前面的#去掉,并在font.sans.seris的第一个位置加上ubuntu已经安装的中文字体:Droid Sans Fallback。如果需要查看ubuntu下有哪些中文字体:

    fc-list :lang=zh-cn

    另外ubuntu中常见的中文字体是文泉驿微黑。

    更多阅读

    http://www.randalolson.com/2014/06/28/how-to-make-beautiful-data-visualizations-in-python-with-matplotlib/

    转载请注明原文地址: https://ju.6miu.com/read-1687.html

    最新回复(0)