Python+Matplotlib科研绘图

5 篇文章 0 订阅
4 篇文章 0 订阅

如何快速使用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

  • 10
    点赞
  • 117
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值