精华内容
下载资源
问答
  • Python+Matplotlib科研绘图

    千次阅读 2020-02-08 00:17:06
    如何快速使用Python Matplotlib 科研绘图 文章目录如何快速使用Python Matplotlib 科研绘图1. 工作环境2. 读写Excel文件3. 绘图格式设置4. 绘制线图5. 更多绘图样式 写在前面: 最近学习和使用了Python Matplotlib ...

    如何快速使用Python Matplotlib 科研绘图


    写在前面: 最近学习和使用了Python Matplotlib 进行科研绘图,对这一方面有了一点学习心得,所以趁着有空把方法总结下,给自己留个念想也希望能给一样需要科研绘图的朋友一点参考。毕竟水平有限,内容有错漏可以留言,我来更改和补充。

    1. 工作环境

    • 配置python环境:建议下载Anconda最新版本和Pycharm Community版,可参考这里下载和安装。Anconda一路按照默认值点确定即可,该软件为开源软件,无需付费,是目前最常用的Python开发环境的集成软件。Pycharm安装后需要选择Anaconda的开发环境。

    • 所需模块:matplotlib、xlrd、xlwt;

      模块安装步骤:安装好Anaconda后在Anaconda Prompt(见图1)或者Window自带的CMD窗口输入以下指令:

      pip install matplotlib xlrd xlwt
      

      安装完成后会有 xxx installed successfully的信息提示

      **图1**图1

    • 验证模块是否安装正确,可以打开編程的交互窗口输入

      import matplotlib,xlrd,xlwt
      

      无报错提示即为环境配置成功(见图2)

      在这里插入图片描述图2

    2. 读写Excel文件

    此部分将介绍如何将excel中的数据提取出来或者将计算出的数据保存到Excel中去。在科研绘图时,必不可免的需要从Excel中获取数据并对数据可视化。

    • 读取数据

      Python读取Excel文档可以使用xlrd模块,主要步骤如下:

      • import xlrd
        
      • 打开Excel文件

        workbook1=xlrd.open_workbook(excel_path)#文件目录需包含文件后缀 .xls
        
      • 获取excel文件中的一个工作簿

        sheet1=workbook1.sheet_by_index(sheet_index)#通过工作簿的顺序索引获取工作簿,索引顺序从0开始
        sheet_names=workbook1.sheet_names()#获取工作簿的名称
        sheet2=workbook1.sheet_by_name(sheet_name)#通过工作簿的名称获取工作簿
        
      • 获取工作簿的行列数

        nr=sheet1.nrows#行数
        nc=sheet1.ncols#列数
        
      • 获取数据

        data=sheet1.row(row_index)#获取当前行数所在行所有单元格内数据组成的列表
        cell_len=sheet1.row_len(row_index)#获取当前行数有效单元格长度
        data=sheet1.row_values(row_index,start_rowx=0,end_rowx=None)#获取某一行中所有单元各数据组成的列表
        data=sheet1.col(col_index,start_colx=0,end_colx=None)#获取某一列中所有单元格对象所组成的列表
        data=sheet1.col_values(col_index,start_colx=0,end_colx=None)#获取某一列中所有单元各数据组成的列表
        data=sheet1.cell(row_index,col_index)#获取单元格对象,(行,列)
        data=sheet1.cell_value(row_index,col_index)#获取单元格对象,(行,列)
        
    • 写入数据:这一部分搬运自此处,详细阅读请至原网站

      • 导入模块

        import xlwt
        #创建一个工作簿,括号中为编码方式
        workbook = xlwt.Workbook(encoding='utf-8')
        
      • 设置格式

        #初始化样式
        style = xlwt.XFStyle()
        #创建字体样式
        font = xlwt.Font()
        font.name = 'Times New Roman'
        font.bold = True#True表示加粗,False表示不加粗
        font.italic = True#斜体
        font.underline = True#下划线
        style.font = font #设定字体样式
        
      • 操作

      #创建sheet表
      #cell_overwrite_ok=True只保留生效最后一次写入
      sheet1 =workbook.add_sheet('sheet1',cell_overwrite_ok=True)
      sheet2 =workbook.add_sheet('sheet2',cell_overwrite_ok=True)
      sheet1.write(0,0,'未设置样式')#(行,列,内容)
      sheet2.write(0,0,'设置样式',style)#含有样式x
      sheet1.col(0).width = 120#设置单元格宽度
      #将工作簿以Excel文件格式保存到本地,注意保存的文件格式
      workbook.save('excel_test.xlsx')
      

    3. 绘图格式设置

    • 创建画图

      import matplotlib.pyplot as plt#导入模块
      plt.figure(num=1,figsize=(2.7,1.8))#创建画图,序号为1,图片大小为2.7*1.8
      
    • 设置字体

      plt.rcParams['axes.unicode_minus'] = False#使用上标小标小一字号
      plt.rcParams['font.sans-serif']=['Times New Roman']
      #设置全局字体,可选择需要的字体替换掉‘Times New Roman’
      #使用黑体'SimHei'作为全局字体,可以显示中文
      #plt.rcParams['font.sans-serif']=['SimHei']
      font1={'family': 'Times New Roman', 'weight': 'light', 'size': 12}#设置字体模板,
      #wight为字体的粗细,可选 ‘normal\bold\light’等
      #size为字体大小
      
    • 图框设置

      #设置图框与图片边缘的距离
      plt.tight_layout(rect=(0,0,1,1))#rect=[left,bottom,right,top]
      #设置x轴
      plt.tick_params(\
          axis='x',#设置x轴
          direction='in',# 小坐标方向,in、out
          which='both',      # 主标尺和小标尺一起显示,major、minor、both
          bottom=True,      #底部标尺打开
          top=False,         #上部标尺关闭
          labelbottom=True, #x轴标签打开
          labelsize=6) #x轴标签大小
      plt.tick_params(\
          axis='y',
          direction='in',
          which='both',     
          left=True,    
          right=False,  
          labelbottom=True) 
      plt.minorticks_on()#开启小坐标
      plt.ticklabel_format(axis='both',style='sci')#sci文章的风格
      

    在这里插入图片描述

    • ticklabel_format定义tick和label的风格,具体参数设置可以参考matplotlib官网的介绍

      KeywordDescription
      axis[ ‘x’ | ‘y’ | ‘both’ ]
      style[ ‘sci’ (or ‘scientific’) | ‘plain’ ] plain turns off scientific notation
      scilimits(m, n), pair of integers; if style is ‘sci’, scientific notation will be used for numbers outside the range 10m to 10n. Use (0,0) to include all numbers. Use (m,m) where m <> 0 to fix the order of magnitude to 10m.
      useOffset[ bool | offset ]; if True, the offset will be calculated as needed; if False, no offset will be used; if a numeric offset is specified, it will be used.
      useLocaleIf True, format the number according to the current locale. This affects things such as the character used for the decimal separator. If False, use C-style (English) formatting. The default setting is controlled by the axes.formatter.use_locale rcparam.
      useMathTextIf True, render the offset and scientific notation in mathtext
    • tick_params定义边框参数,具体参数设置可以参考matplotlib官网的介绍

      Parameters:axis : {‘x’, ‘y’, ‘both’}, optionalWhich axis to apply the parameters to.
      Other Parameters:axis : {‘x’, ‘y’, ‘both’}Axis on which to operate; default is ‘both’.reset : boolIf True, set all parameters to defaults before processing other keyword arguments. Default is False.which : {‘major’, ‘minor’, ‘both’}Default is ‘major’; apply arguments to which ticks.direction : {‘in’, ‘out’, ‘inout’}Puts ticks inside the axes, outside the axes, or both.length : floatTick length in points.width : floatTick width in points.color : colorTick color; accepts any mpl color spec.pad : floatDistance in points between tick and label.labelsize : float or strTick label font size in points or as a string (e.g., ‘large’).labelcolor : colorTick label color; mpl color spec.colors : colorChanges the tick color and the label color to the same value: mpl color spec.zorder : floatTick and label zorder.bottom, top, left, right : boolWhether to draw the respective ticks.labelbottom, labeltop, labelleft, labelright : boolWhether to draw the respective tick labels.labelrotation : floatTick label rotationgrid_color : colorChanges the gridline color to the given mpl color spec.grid_alpha : floatTransparency of gridlines: 0 (transparent) to 1 (opaque).grid_linewidth : floatWidth of gridlines in points.grid_linestyle : stringAny valid Line2D line style spec.
    • tight_layout调整图片的填充间距,具体参数设置可以参考matplotlib官网的介绍

      Parameters:pad : floatPadding between the figure edge and the edges of subplots, as a fraction of the font size.h_pad, w_pad : float, optionalPadding (height/width) between edges of adjacent subplots, as a fraction of the font size. Defaults to pad.rect : tuple (left, bottom, right, top), optionalA rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1).
    • 创建标签和标题

      plt.title("图片标题",fontdict = font1)#标题
      plt.ylabel('Value/ $\mathregular{min^{-1}}$',fontdict=font1)#$\mathregular{min^{-1}}$label的格式,^{-1}为上标
      plt.xlabel('Time/min',fontdict=font1)
      plt.legend(loc="best",scatterpoints=1,prop=font0,shadow=True,frameon=False)#添加图例,loc控制图例位置,“best”为最佳位置,“bottom”,"top",“topringt"等,shadow为图例边框阴影,frameon控制是否有边框
      

      在这里插入图片描述图例

    • 画图

      plt.plot(x,y,'k--',lw=1.5,label="line1")#'k--'为直线的格式,k表示颜色黑色,--表示虚线
      #--可以替换为其他符号
       plt.scatter(x,y,marker='o',color='r',s=10,label="line2")#marker为点的形式,color为颜色
       #
      
      • marker的种类,引用自matplotlib官网
        在这里插入图片描述

      • 引用matplotlib的color使用

        Matplotlib recognizes the following formats to specify a color:

        • an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3));
        • a hex RGB or RGBA string (e.g., '#0f0f0f' or '#0f0f0f80'; case-insensitive);
        • a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5');
        • one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};
        • a X11/CSS4 color name (case-insensitive);
        • a name from the xkcd color survey, prefixed with 'xkcd:' (e.g., 'xkcd:sky blue'; case insensitive);
        • one of the Tableau Colors from the ‘T10’ categorical palette (the default color cycle): {'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} (case-insensitive);
        • a “CN” color spec, i.e. 'C' followed by a number, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing is intended to occur at rendering time, and defaults to black if the cycle does not include color.
    • 查看和保存图片

      plt.show()#查看图片
      plt.savefig("figure_1.eps",format="eps",dpi=600)
      plt.savefig("figure_1.tif",format="tif",dpi=600)
      plt.savefig("figure_1.png",format="png",dpi=600)
      #保存不同的图片格式,dpi为图片的精细程度,dpi越高图片越精细,也更大
      

    4. 绘制线图

    本部分为一个具体的绘图例子,介绍代码的使用

    import matplotlib.pyplot as plt#导入模块
    #先设置需要画图的数据
    x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
    y1=[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35]
    y2=[19,21,23,25,27,29,31,33,35,37,11,13,15,17,5,7,9,1]
    #
    plt.figure(num=1,figsize=(6,4))#创建画图,序号为1,图片大小为2.7*1.8
    plt.rcParams['axes.unicode_minus'] = False#使用上标小标小一字号
    plt.rcParams['font.sans-serif']=['Times New Roman']
    #设置全局字体,可选择需要的字体替换掉‘Times New Roman’
    #使用黑体作为全局字体,可以显示中文
    #plt.rcParams['font.sans-serif']=['SimHei']
    font1={'family': 'Times New Roman', 'weight': 'light', 'size': 12}#设置字体模板,
    font2={'family': 'Times New Roman', 'weight': 'light', 'size': 16}#设置字体模板,
    #wight为字体的粗细,可选 ‘normal\bold\light’等
    #size为字体大小
    plt.title("Title",fontdict=font2)#标题
    plt.plot(x,y1,'r^',lw=1.5,label="line1")#红色直线
    plt.plot(x,y2,'b-',lw=1.5,label="line2")#蓝色三角
    plt.ylabel('Value/ $\mathregular{min^{-1}}$',fontdict=font1)#$\mathregular{min^{-1}}$label的格式,^{-1}为上标
    plt.xlabel('Time/min',fontdict=font1)
    plt.legend(loc="best",scatterpoints=1,prop=font1,shadow=True,frameon=False)#添加图例,\
    # loc控制图例位置,“best”为最佳位置,“bottom”,"top",“topringt"等,\
    # shadow为图例边框阴影,frameon控制是否有边框
    plt.minorticks_on()#开启小坐标
    #设置图框与图片边缘的距离
    #设置x轴
    plt.tick_params(\
        axis='x',#设置x轴
        direction='in',# 小坐标方向,in、out
        which='both',      # 主标尺和小标尺一起显示,major、minor、both
        bottom=True,      #底部标尺打开
        top=False,         #上部标尺关闭
        labelbottom=True, #x轴标签打开
        labelsize=12) #x轴标签大小
    plt.tick_params(\
        axis='y',
        direction='in',
        which='both',
        left=True,
        right=False,
        labelbottom=True,
        labelsize=12)
    plt.ticklabel_format(axis='both',style='sci')#sci文章的风格
    plt.tight_layout(rect=(0,0,1,1))#rect=[left,bottom,right,top]
    plt.savefig("example.png",format="png",dpi=600)
    plt.show()
    
    • 运行后可以得到如下的图片

    在这里插入图片描述

    • eps格式的图片结合Adobe Illustrator(AI)使用可以更好地对原始图片进行修改和补充,是科研绘图的高阶使用(目前只是简单地尝试过,后续更新。。。)

    5. 更多绘图样式

    科研绘图的图片格式设置是绘图的第一步,建立自己的风格确定文章绘图模板,有了模板,只要将其中的线图、点图更换为自己需要的柱状图、饼图以及其他的样式就可以了。更多的绘图样式可以参考Matplotlib中的example

    展开全文
  • Python matplotlib绘图 自己的科研风?

    千次阅读 2019-05-06 21:52:14
    Python matplotlib绘图 如何科研风?风点线图、散点图、网络图、条形图 dpiccolo,个人绘图笔记 个人常用的内容:绘图风格、字体类型、大小、marker、图例位置 官网最直接、全面:Pyplot function overview 1...

    Python matplotlib绘图 如何科研风?点线图、散点图、网络图、条形图

    dpiccolo,个人绘图笔记

    个人常用的内容:绘图风格、字体类型、大小、marker、图例位置

    官网最直接、全面:Pyplot function overview

    1.绘图风格

    matplotlib自带的风格课参考Matplotlib Style Gallery
    Customizing plots with style sheets
    另外还有seaborn库可以更好地学习。
    线型和marker类型等,可参考plt 绘图 知识点整理

    plt.style.use("seaborn-deep")
    

    个人常用:
    ggplot
    在这里插入图片描述
    bmh
    在这里插入图片描述
    grayscale
    在这里插入图片描述
    seaborn-deep
    在这里插入图片描述

    2.面向对象的基本绘图方式

    快速绘图中必须要考虑操作对象,面向对象绘图中加坐标名字和标题等要加set_

    
    __date__ = '2019/4/1 23:13'
    __author__ = 'dpiccolo'
    import numpy as np
    import matplotlib.pyplot as plt
    
    from pylab import mpl
    mpl.rcParams['font.sans-serif'] = ['Times New Roman'] # 指定默认字体
    mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
    
    samplenum1=np.arange(25,500+2,25)
    x25 = samplenum1
    samplenum2=np.arange(10,200+2,10)
    x10 = samplenum2
    samplenum3=np.arange(2,40+2,2)
    x2 = samplenum3
    
    accuracy10sigmoid_test=[0.863, 0.898, 0.964, 0.985, 0.975, 0.985, 0.989, 0.992, 0.992, 0.99, 0.989, 0.991, 0.988, 0.995, 0.994, 0.995, 1.0, 0.999, 0.996, 0.995]
    accuracy10tanh_test=[0.88, 0.968, 0.99, 0.985, 0.987, 0.988, 0.979, 0.986, 0.989, 0.988, 0.99, 0.987, 0.985, 0.993, 0.992, 0.993, 0.989, 0.99, 0.981, 0.991]
    accuracy10relu_test=[0.931, 0.9, 0.933, 0.947, 0.953, 0.967, 0.98, 0.985, 0.973, 0.981, 0.985, 0.985, 0.986, 0.979, 0.985, 0.984, 0.984, 0.982, 0.978, 0.976]
    #面向对象的绘图方式
    rect1 = [0.14, 0.35, 0.77, 0.6]
    fig,ax = plt.subplots()
    ax.figsize=(48,48)
    plt.rcParams['figure.figsize'] = (6.0, 4.0)
    plt.rcParams['image.interpolation'] = 'nearest' # 设置 interpolation style
    plt.rcParams['image.cmap'] = 'gray' # 设置 颜色 style
    plt.rcParams['savefig.dpi'] = 300 #图片像素
    plt.rcParams['figure.dpi'] = 300 #分辨率
    
    ins0=ax.plot(x10,accuracy10tanh_test, label = 'tanh',marker='o')
    ins1=ax.plot(x10,accuracy10relu_test, label = 'relu',marker='s')
    ins2=ax.plot(x10,accuracy10sigmoid_test, label = 'sigmoid',marker='v')
    lns = ins0+ins1+ins2
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc="lower right")#loc="lower right" 图例右下角
    ax.set_xlabel("Iteration")
    ax.set_ylabel("Accuracy")
    #ax.set_title("xxx0-10")
    ax.set_xticks(x10)
    ax.set_yticks([0.7,0.9,0.95,1.0])
    #ax.grid()
    plt.savefig('xxx0-10-0.png')
    
    
    
    

    结果图:
    在这里插入图片描述

    3.pylab神技——pylab.rcParams.update()

    一个比较全面的绘图属性设置,包括字号、字体类型、颜色、线宽等等。

    具体使用请参照Customizing matplotlib,十分推荐。

    下面是一个实例。字号设置均为10,字体选用Times New Romanfigsize7x3dpi1000,最后保存绘图分辨率(未裁多余白边时)为7000x3000,剪裁多余白边后为6147x2909.

    保存时裁多余白边 bbox_inches='tight'

    plt.savefig('kdd-iteration.eps', dpi=1000, bbox_inches='tight')
    
    __date__ = '2019/4/3 22:34'
    __author__ = 'dpiccolo'
    import matplotlib.pyplot as plt
    import matplotlib.pylab as pylab
    import numpy as np
    from PIL import Image
    
    myparams = {
    
       'axes.labelsize': '10',
    
       'xtick.labelsize': '10',
    
       'ytick.labelsize': '10',
    
       'lines.linewidth': 1,
    
       'legend.fontsize': '10',
    
       'font.family': 'Times New Roman',
    
       'figure.figsize': '7, 3'  #图片尺寸
    
    }
    
    pylab.rcParams.update(myparams)  #更新自己的设置
    # line_styles=['ro-','b^-','gs-','ro--','b^--','gs--']  #线型设置
    samplenum2=np.arange(10,200+2,10)
    x10 = samplenum2
    samplenum3=np.arange(2,40+2,2)
    x2 = samplenum3
    #原始数据0
    accuracy10sigmoid_test=[0.595,0.564,0.556,0.6,0.563,0.547,0.81,0.874,0.895,0.923,0.93,0.936,0.953,0.95,0.96,0.955,0.966,0.964,0.973,0.979]
    accuracy10tanh_test=[0.879,0.967,0.98,0.986,0.982,0.987,0.988,0.987,0.991,0.994,0.994,0.992,0.995,0.985,0.987,0.985,0.987,0.992,0.988,0.992]
    accuracy10relu_test=[0.788,0.804,0.786,0.809,0.791,0.796,0.82,0.812,0.816,0.801,0.798,0.808,0.844,0.994,0.991,0.991,0.993,0.995,0.995,0.984]
    #原始数据1
    accuracy2relu_test=[0.207,0.198,0.678,0.665,0.78,0.78,0.79,0.783,0.779,0.779,0.786,0.776,0.801,0.788,0.793,0.79,0.786,0.776,0.791,0.8]
    accuracy2tanh_test=[0.241,0.618,0.588,0.579,0.577,0.614,0.741,0.852,0.903,0.933,0.961,0.974,0.981,0.979,0.984,0.984,0.981,0.98,0.981,0.987]
    accuracy2sigmoid_test=[0.001,0.002,0.572,0.568,0.564,0.601,0.587,0.568,0.536,0.58,0.557,0.567,0.601,0.575,0.584,0.559,0.565,0.583,0.58,0.561]
    #
    fig1 = plt.figure(1)
    axes1 = plt.subplot(121)#figure1的子图1为axes1
    plt.plot(x2,accuracy2tanh_test, label = 'tanh',marker='o',
            markersize=5)
    plt.plot(x2,accuracy2relu_test, label = 'relu',marker='s',
            markersize=5)
    plt.plot(x2,accuracy2sigmoid_test, label = 'sigmoid',marker='v',
            markersize=5)
    axes1.set_yticks([0.7, 0.9, 0.95, 1.0])
    #axes1 = plt.gca()
    #axes1.grid(True)  # add grid
    plt.legend(loc="lower right")  #图例位置 右下角
    plt.ylabel('Accuracy') 
    plt.xlabel('(a)Iteration:40 ') 
    
    axes2 = plt.subplot(122)
    plt.plot(x10,accuracy10tanh_test, label = 'tanh',marker='o',
            markersize=5)
    plt.plot(x10,accuracy10relu_test, label = 'relu',marker='s',
            markersize=5)
    plt.plot(x10,accuracy10sigmoid_test, label = 'sigmoid',marker='v',
            markersize=5)
    axes2.set_yticks([0.7, 0.9, 0.95, 1.0])
    #axes2 = plt.gca()
    #axes2.grid(True)  # add grid
    plt.legend(loc="lower right") 
    #plt.ylabel('Accuracy')  
    plt.xlabel('(b)Iteration:200 ') 
    plt.savefig('kdd-iteration.eps', dpi=1000, bbox_inches='tight')#bbox_inches='tight'会裁掉多余的白边
    #注意.show()操作后会默认打开一个空白fig,此时保存,容易出现保存的为纯白背景,所以请在show()操作前保存fig.
    plt.show()
    
    

    结果图:
    在这里插入图片描述

    4.条形图、网络图、散点图的绘制

    画散点图,主要用到scatter
    画网络图,主要用到networkx库。

    下面有几个,来自Python科学画图小结的例子。

    条形图绘制

    import scipy.io
    import numpy as np
    import matplotlib.pylab as pylab
    import matplotlib.pyplot as plt
    import matplotlib.ticker as mtick
    params={
       'axes.labelsize': '35',
       'xtick.labelsize':'27',
       'ytick.labelsize':'27',
       'lines.linewidth':2 ,
       'legend.fontsize': '27',
       'figure.figsize'   : '24, 9'
    }
    pylab.rcParams.update(params)
    
    y1 = [9.79,7.25,7.24,4.78,4.20]
    y2 = [5.88,4.55,4.25,3.78,3.92]
    y3 = [4.69,4.04,3.84,3.85,4.0]
    y4 = [4.45,3.96,3.82,3.80,3.79]
    y5 = [3.82,3.89,3.89,3.78,3.77]
    
    ind = np.arange(5)                # the x locations for the groups
    width = 0.15
    plt.bar(ind,y1,width,color = 'blue',label = 'm=2')  
    plt.bar(ind+width,y2,width,color = 'g',label = 'm=4') # ind+width adjusts the left start location of the bar.
    plt.bar(ind+2*width,y3,width,color = 'c',label = 'm=6')
    plt.bar(ind+3*width,y4,width,color = 'r',label = 'm=8')
    plt.bar(ind+4*width,y5,width,color = 'm',label = 'm=10')
    plt.xticks(np.arange(5) + 2.5*width, ('10%','15%','20%','25%','30%'))
    
    plt.xlabel('Sample percentage')
    plt.ylabel('Error rate')
    
    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)   
    # Set the formatter
    axes = plt.gca()   # get current axes
    axes.yaxis.set_major_formatter(xticks) # set % format to ystick.
    axes.grid(True)
    plt.legend(loc="upper right")
    #plt.savefig('errorRate.eps', format='eps',dpi = 1000,bbox_inches='tight')
    plt.savefig('errorRate.png',dpi = 1000,bbox_inches='tight')
    plt.show()
    

    在这里插入图片描述
    网络图绘制

    import networkx as nx
    import pylab as plt
    
    g = nx.Graph()
    g.add_edge(1,2,weight = 4)
    g.add_edge(1,3,weight = 7)
    g.add_edge(1,4,weight = 8)
    g.add_edge(1,5,weight = 3)
    g.add_edge(1,9,weight = 3) 
    g.add_edge(1,6,weight = 6)
    g.add_edge(6,7,weight = 7)
    g.add_edge(6,8,weight = 7)  
    g.add_edge(6,9,weight = 6) 
    g.add_edge(9,10,weight = 7) 
    g.add_edge(9,11,weight = 6) 
    
    fixed_pos = {1:(1,1),2:(0.7,2.2),3:(0,1.8),4:(1.6,2.3),5:(2,0.8),6:(-0.6,-0.6),7:(-1.3,0.8), 8:(-1.5,-1), 9:(0.5,-1.5), 10:(1.7,-0.8), 11:(1.5,-2.3)} #set fixed layout location
    #pos=nx.spring_layout(g) # or you can use other layout set in the module
    nx.draw_networkx_nodes(g,pos = fixed_pos,nodelist=[1,2,3,4,5],
    node_color = 'g',node_size = 600)
    nx.draw_networkx_edges(g,pos = fixed_pos,edgelist=[(1,2),(1,3),(1,4),(1,5),(1,9)],edge_color='g',width = [4.0,4.0,4.0,4.0,4.0],label = [1,2,3,4,5],node_size = 600)
    nx.draw_networkx_nodes(g,pos = fixed_pos,nodelist=[6,7,8],
    node_color = 'r',node_size = 600)
    nx.draw_networkx_edges(g,pos = fixed_pos,edgelist=[(6,7),(6,8),(1,6)],width = [4.0,4.0,4.0],edge_color='r',node_size = 600)
    nx.draw_networkx_nodes(g,pos = fixed_pos,nodelist=[9,10,11],
    node_color = 'b',node_size = 600)
    nx.draw_networkx_edges(g,pos = fixed_pos,edgelist=[(6,9),(9,10),(9,11)],width = [4.0,4.0,4.0],edge_color='b',node_size = 600)
    
    plt.text(fixed_pos[1][0],fixed_pos[1][1]+0.2, s = '1',fontsize = 40)
    plt.text(fixed_pos[2][0],fixed_pos[2][1]+0.2, s = '2',fontsize = 40)
    plt.text(fixed_pos[3][0],fixed_pos[3][1]+0.2, s = '3',fontsize = 40)
    plt.text(fixed_pos[4][0],fixed_pos[4][1]+0.2, s = '4',fontsize = 40)
    plt.text(fixed_pos[5][0],fixed_pos[5][1]+0.2, s = '5',fontsize = 40)
    plt.text(fixed_pos[6][0],fixed_pos[6][1]+0.2, s = '6',fontsize = 40)
    plt.text(fixed_pos[7][0],fixed_pos[7][1]+0.2, s = '7',fontsize = 40)
    plt.text(fixed_pos[8][0],fixed_pos[8][1]+0.2, s = '8',fontsize = 40)
    plt.text(fixed_pos[9][0],fixed_pos[9][1]+0.2, s = '9',fontsize = 40)
    plt.text(fixed_pos[10][0],fixed_pos[10][1]+0.2, s = '10',fontsize = 40)
    plt.text(fixed_pos[11][0],fixed_pos[11][1]+0.2, s = '11',fontsize = 40)
    plt.show()
    

    在这里插入图片描述

    展开全文
  • Matplotlib科研画图.图基本框架. Sep 6, 2020. Berkeley, USA. step 1 f_size = 10 #字体大小,用于label和ticks等 font = {'size': f_size}#字体大小用于label和ticks等 plt.style.use('default') #基本风格,...

    Matplotlib科研画图.图基本框架. Sep 6, 2020. Berkeley, USA.

    #step 1
    
    f_size = 10  #字体大小,用于label和ticks等
    font = {'size': f_size} #字体大小用于label和ticks等
    plt.style.use('default') #基本风格,包括画框线粗,预设调色盘等
    plt.rcParams['font.family'] = 'Arial' #字体样式
    plt.rcParams['font.size'] = 9 #字体大小,也可通过上面的font局部调整
    
    #step 2
    
    fig = plt.figure(figsize=(3.5, 4)) #构建图
    plt.subplots_adjust(left=0.14, bottom=0.13, right=1.03, top=0.96, wspace=0, hspace=0.5) #调整图和子图位置
    ax= fig.add_subplot(1, 1, 1) #构建轴
    
    #step 3
    
    ax.plot() #具体画图
    
    #step 4
    
    ax.set_xlabel('x', font) #x坐标,font在这里控制字体
    ax.set_ylabel('y', font) #y坐标,font在这里控制字体
    ax.tick_params(axis="x", labelsize=f_size-1, labelrotation=45, labelcolor="k") #控#制刻度内容,字体大小,方向旋转,颜色
    ax.legend(loc=(0.1,0.1), ncol=1, frameon=False, labelspacing=0.2, columnspacing=0.7, fontsize=f_size-1) #控制legend
    

     

    展开全文
  • matplotlib科研绘图---Times New Roman字体设置

    千次阅读 多人点赞 2020-08-28 16:28:20
    matplotlib图例、标签、坐标轴刻度的字体设置 一、法一 plt.figure(figsize=[15,8]) plt.scatter(X, Y, label = 'RealValue') plt.plot(X, func(X, a, b), 'red', label = 'CurveLine') plt.title(station, fontdict...

    matplotlib科研绘图—Times New Roman字体设置

    一、法一

    plt.figure(figsize=[15,8])
    plt.scatter(X, Y, label = 'RealValue')
    plt.plot(X, func(X, a, b), 'red', label = 'CurveLine')
    plt.title(station, fontdict={'family' : 'Times New Roman', 'size'   : 16})
    plt.ylabel('Clocks($\mu S$)', fontdict={'family' : 'Times New Roman', 'size'   : 16})
    plt.xlabel('Time', fontdict={'family' : 'Times New Roman', 'size'   : 16})
    plt.yticks(fontproperties = 'Times New Roman', size = 14)
    plt.xticks(fontproperties = 'Times New Roman', size = 14)
    plt.legend(prop={'family' : 'Times New Roman', 'size'   : 16})
    plt.savefig('./stationClocks/' + station + '.ps', dpi = 200)
    plt.show()
    

    二、法二

    解决字体不一致的方法
    将全局字体改为Times New Roman

    import matplotlib.pyplot as plt
    plt.rc('font',family='Times New Roman')
    

    解决Times New Roman加粗的问题

    del matplotlib.font_manager.weight_dict['roman']
    matplotlib.font_manager._rebuild()
    

    三、一些参数

    matplotlib说明框中字体粗细
    用默认的字体时,'weight’的变化是可以改变字体粗细的,以下是代码

    import matplotlib.pyplot as plt
    
    styles=['normal','italic','oblique']
    weights=['ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black']
    plt.figure(figsize=(15,3)) 
    for i in range(len(styles)):
        for j in range(len(weights)):
            font={'style':styles[i],'weight':weights[j]}
            plt.subplot(len(styles),len(weights),i*len(weights)+j+1) 
            plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'b', label='VGG-16')
            plt.legend(loc='upper right', prop=font)
    plt.savefig('style.png')
    

    一旦把字体设定为’Times New Roman’,'weight’就没办法调节说明框中字体的粗细

    import matplotlib.pyplot as plt
    
    styles=['normal','italic','oblique']
    weights=['ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black']
    plt.figure(figsize=(15,3)) 
    for i in range(len(styles)):
        for j in range(len(weights)):
            font={'family' : 'Times New Roman','style':styles[i],'weight':weights[j]}
            plt.subplot(len(styles),len(weights),i*len(weights)+j+1) 
            plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'b', label='VGG-16')
            plt.legend(loc='upper right', prop=font)
    plt.savefig('style.png')
    

    四、Matplotlib画各种论文图

    # coding=utf-8
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.rcParams['font.sans-serif'] = ['Arial']  # 如果要显示中文字体,则在此处设为:SimHei
    plt.rcParams['axes.unicode_minus'] = False  # 显示负号
    
    x = np.array([1, 2, 3, 4, 5, 6])
    VGG_supervised = np.array([2.9749694, 3.9357018, 4.7440844, 6.482254, 8.720203, 13.687582])
    VGG_unsupervised = np.array([2.1044724, 2.9757383, 3.7754183, 5.686206, 8.367847, 14.144531])
    ourNetwork = np.array([2.0205495, 2.6509762, 3.1876223, 4.380781, 6.004548, 9.9298])
    
    # label在图示(legend)中显示。若为数学公式,则最好在字符串前后添加"$"符号
    # color:b:blue、g:green、r:red、c:cyan、m:magenta、y:yellow、k:black、w:white、、、
    # 线型:-  --   -.  :    ,
    # marker:.  ,   o   v    <    *    +    1
    plt.figure(figsize=(10, 5))
    plt.grid(linestyle="--")  # 设置背景网格线为虚线
    ax = plt.gca()
    ax.spines['top'].set_visible(False)  # 去掉上边框
    ax.spines['right'].set_visible(False)  # 去掉右边框
    
    
    plt.plot(x, VGG_supervised, marker='o', color="blue", label="VGG-style Supervised Network", linewidth=1.5)
    plt.plot(x, VGG_unsupervised, marker='o', color="green", label="VGG-style Unsupervised Network", linewidth=1.5)
    plt.plot(x, ourNetwork, marker='o', color="red", label="ShuffleNet-style Network", linewidth=1.5)
    
    group_labels = ['Top 0-5%', 'Top 5-10%', 'Top 10-20%', 'Top 20-50%', 'Top 50-70%', ' Top 70-100%']  # x轴刻度的标识
    plt.xticks(x, group_labels, fontsize=12, fontweight='bold')  # 默认字体大小为10
    plt.yticks(fontsize=12, fontweight='bold')
    # plt.title("example", fontsize=12, fontweight='bold')  # 默认字体大小为12
    plt.xlabel("Performance Percentile", fontsize=13, fontweight='bold')
    plt.ylabel("4pt-Homography RMSE", fontsize=13, fontweight='bold')
    plt.xlim(0.9, 6.1)  # 设置x轴的范围
    plt.ylim(1.5, 16)
    
    # plt.legend()          #显示各曲线的图例
    plt.legend(loc=0, numpoints=1)
    leg = plt.gca().get_legend()
    ltext = leg.get_texts()
    plt.setp(ltext, fontsize=12, fontweight='bold')  # 设置图例字体的大小和粗细
    
    plt.savefig('./filename.svg', format='svg')  # 建议保存为svg格式,再用inkscape转为矢量图emf后插入word中
    plt.show()
    

    在这里插入图片描述

    展开全文
  • Matplotlib科研画图.图基本框架. Sep 6, 2020. Berkeley, USA.step 1f_size = 10 #字体大小,用于label和ticks等font = {'size': f_size}#字体大小用于label和ticks等plt.style.use('default') #基本风格,包括画框...
  • 本文分享了50个令人眼前一亮的Matplotlib可视化项图表,每个图表都有其相应的生成代码,并将它们分为了关联、偏差、排序、分布、组成、变化、分组等7个类别,是科研作图时很好的参考。 本文由lqy上传,翻译自...
  • Matplotlib科研画图.调色盘颜色提取和更改 提取调色盘颜色 palette 提取seaborn调色盘颜色 plt.style.use('default') #清空之前调色盘更改 sns.set()#将调色盘设置为seaborn color_palette_sns = plt.rcParams['...
  • python中关于图的样式设置没有更多的用法说明,就找了参考文章,原文链接放在这里:Python+Matplotlib科研绘图_子语默涵的博客-CSDN博客_python科研绘图 绘图样式参考官方文档:科研绘图的图片格式设置是绘图的第一...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,233
精华内容 493
关键字:

matplotlib科研绘图