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

文章目录

  • 如何快速使用Python Matplotlib 科研绘图
    • 1. 工作环境
    • 2. 读写Excel文件
    • 3. 绘图格式设置
    • 4. 绘制线图
    • 5. 更多绘图样式

写在前面: 最近学习和使用了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

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

    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、outwhich='both',      # 主标尺和小标尺一起显示,major、minor、bothbottom=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官网的介绍

    Keyword Description
    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.
    useLocale If 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.
    useMathText If 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、outwhich='both',      # 主标尺和小标尺一起显示,major、minor、bothbottom=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科研绘图相关推荐

  1. python绘图实例-Python matplotlib基础绘图函数示例

    原标题:Python matplotlib基础绘图函数示例 Pyplot基础图标函数: 函数 说明 plt.plot(x,y,fmt,-) 绘制一个坐标图 plt.boxplot(data,notch ...

  2. Python Matplotlib 3D绘图详解(汇总)

    Python Matplotlib 3D绘图详解(汇总) 最初开发的 Matplotlib,仅支持绘制 2d 图形,后来随着版本的不断更新, Matplotlib 在二维绘图的基础上,构建了一部分较为 ...

  3. python matplotlib各种绘图类型完整总结

    文章目录 1. Matplotlib图像基础 1.1 __基本绘图实例:sin.cos函数图__ 1.2 plot()函数详解 1.3 __matplotlib中绘图的默认配置__ 1.4 __设置图 ...

  4. Python Matplotlib 花式绘图和中文字符显示、散点图、设置网格和散点函数拟合

    目录 1.隔段的bar绘图 2.显示中文字符的曲线绘制 3.需要注意的内容 4.Python绘图库Matplotlib.pyplot之网格线设置(plt.grid()) 5.绘制散点分布图 6.调整图 ...

  5. Python matplotlib高级绘图详解

    Pyplot绘图结构 Aritists matplotlib API包含有三层: backend_bases.FigureCanvas : 图表的绘制领域 backend_bases.Renderer ...

  6. Python matplotlib 批量绘图内存不够问题(Out of memory)

    在使用matplotlib批量绘制图片时,内存占用会随着绘制图片数量的增加而增加,最终内存不够,提示为:Out of memory 解决办法 1.在导入matplotlib库后,且在matplotli ...

  7. Python — matplotlib.pyplot 绘图模块及常用函数

    目录 1. 基本用法与折线图 pyplot 模块的常用函数 折线图函数: matplotlib.pyplot.plot() 常用 format_string 参数 常用函数 grid () 控制各轴网 ...

  8. python matplotlib 实时绘图

    有时候,需要获取动态数据,并实时绘图.比如从串口读取数据等等 import matplotlib.pyplot as pltax = [] # 定义一个 x 轴的空列表用来接收动态的数据 ay = [ ...

  9. python绘图实例-Python——matplotlib基础绘图函数示例

    1. 2.饼图 (1) import matplotlib.pyplot as plt labels='frogs','hogs','dogs','logs'% sizes=[15,30,45,10] ...

  10. Python matplotlib库绘图时设置标题 (label)、坐标轴 (axis) 和标注 (legend)的字体及大小

    文章目录 1 标题 2 坐标轴 3 标注 4 示例 5 展示 6 说明 1 标题 plt.xlabel('False positive rate', fontdict={"family&qu ...

最新文章

  1. 未来已来:5G将在这88个方面影响我们的工作和生活
  2. linux搭建vsftpd虚拟用户访问
  3. 计算机应用工作技能与经验,关于计算机应用技能人才培养模式的思考
  4. 学python需要什么文化基础-数据分析需要掌握那些基础知识?
  5. MyCat学习:使用MySQL搭建主从复制(一主一从模式)
  6. [转]Zookeeper入门看这篇就够了
  7. Node.js -- Stream 使用小例 ( 流运用 :读取、写入、写出、拷贝)
  8. LeetCode 2135. 统计追加字母可以获得的单词数(位运算+哈希)
  9. errorattributes 过时_苹果官方确认:iPhone 5c 已被列为过时产品
  10. Java 13新特性:switch表达式,文本块
  11. Linux上安装gcc
  12. Windows删除服务
  13. solidworks2016安装教程及破解方法
  14. 高通CSR8670蓝牙音频芯片怎么样?CSR8670处理器参数介绍
  15. 第七章 算术操作指令的实现
  16. java 递归死循环_java嵌套事物与递归调用避免死循环问题
  17. Sensor 数据整理
  18. Python基于Django航空飞机票预定网站设计
  19. Windows 取证之$MFT
  20. 线稿上色V3(比V2差别在于这个参考图的处理方式),并且更好用哦

热门文章

  1. Redis数据丢失问题
  2. DLL load failed while importing rdBase
  3. plsql打开sql窗口快捷键_PL/SQL 快捷键设置
  4. 芝麻小客服电脑版新增网址自带openid功能,聊天界面改版,新增通用设置
  5. android 打apk文件怎么打开方式,apk文件怎么打开
  6. android启用hdcp_如何在Android Auto上启用开发人员设置
  7. 微信登录显示网页无法连接服务器地址,手机微信登陆不了?
  8. PaddleOCR整体了解
  9. 怎样组建家庭计算机网络,不要再求人了,教你最详细的家庭网络组建方法。
  10. 不确定性,进化与经济理论