SCI论文绘图—Python绘图常用模板及技巧

关注 M r . m a t e r i a l   , \color{Violet} \rm Mr.material\ , Mr.material , 更 \color{red}{更} 多 \color{blue}{多} 精 \color{orange}{精} 彩 \color{green}{彩}


主要专栏内容包括:
  †《LAMMPS小技巧》: ‾ \textbf{ \underline{\dag《LAMMPS小技巧》:}}  LAMMPS小技巧》: 主要介绍采用分子动力学( L a m m p s Lammps Lammps)模拟相关安装教程、原理以及模拟小技巧(难度: ★ \bigstar
  ††《LAMMPS实例教程—In文件详解》: ‾ \textbf{ \underline{\dag\dag《LAMMPS实例教程—In文件详解》:}}  ††LAMMPS实例教程—In文件详解》: 主要介绍采用分子动力学( L a m m p s Lammps Lammps)模拟相关物理过程模拟。(包含:热导率计算、定压比热容计算,难度: ★ \bigstar ★ \bigstar ★ \bigstar
  †††《Lammps编程技巧及后处理程序技巧》: ‾ \textbf{ \underline{\dag\dag\dag《Lammps编程技巧及后处理程序技巧》:}}  †††Lammps编程技巧及后处理程序技巧》: 主要介绍针对分子模拟的动力学过程(轨迹文件)进行后相关的处理分析(需要一定编程能力。难度: ★ \bigstar ★ \bigstar ★ \bigstar ★ \bigstar ★ \bigstar )。
  ††††《分子动力学后处理集成函数—Matlab》: ‾ \textbf{ \underline{\dag\dag\dag\dag《分子动力学后处理集成函数—Matlab》:}}  ††††《分子动力学后处理集成函数—Matlab》: 主要介绍针对后处理过程中指定函数,进行包装,方便使用者直接调用(需要一定编程能力,难度: ★ \bigstar ★ \bigstar ★ \bigstar ★ \bigstar )。
  †††††《SCI论文绘图—Python绘图常用模板及技巧》: ‾ \textbf{ \underline{\dag\dag\dag\dag\dag《SCI论文绘图—Python绘图常用模板及技巧》:}}  †††††SCI论文绘图—Python绘图常用模板及技巧》: 主要介绍针对处理后的数据可视化,并提供对应的绘图模板(需要一定编程能力,难度: ★ \bigstar ★ \bigstar ★ \bigstar ★ \bigstar )。
  ††††††《分子模拟—Ovito渲染案例教程》: ‾ \textbf{ \underline{\dag\dag\dag\dag\dag\dag《分子模拟—Ovito渲染案例教程》:}}  ††††††《分子模拟—Ovito渲染案例教程》: 主要采用 O v i t o \rm Ovito Ovito软件,对 L a m m p s \rm Lammps Lammps 生成的轨迹文件进行渲染(难度: ★ \bigstar ★ \bigstar )。

  专栏说明(订阅后可浏览对应专栏全部博文): ‾ \color{red}{\textbf{ \underline{专栏说明(订阅后可浏览对应专栏全部博文):}}}  专栏说明(订阅后可浏览对应专栏全部博文):
注意: \color{red} 注意: 注意:如需只订阅某个单独博文,请联系博主邮箱咨询。 l a m m p s _ m a t e r i a l s @ 163. c o m \rm lammps\_materials@163.com lammps_materials@163.com

♠ \spadesuit † \dag 开源后处理集成程序:请关注专栏《LAMMPS后处理——MATLAB子函数合集整理》
♠ \spadesuit † \dag † \dag 需要付费定制后处理程序请邮件联系: l a m m p s _ m a t e r i a l s @ 163. c o m \rm lammps\_materials@163.com lammps_materials@163.com


♠ \spadesuit ♠ \spadesuit L a m m p s Lammps Lammps 后处理及编程技巧第一次线上分享论坛( 2021.11.20 2021.11.20 2021.11.20):
视频链接 \color{red}{视频链接} 视频链接(请点击)
资料下载 \color{red}{资料下载} 资料下载 (请点击)
提取码: o a x k 提取码:\color{red}{oaxk} 提取码:oaxk

欢迎关注公众号 : 分子模拟  M D   C l u b   ( M r _ M a t e r i a l s ) \rm \color{red} 欢迎关注公众号:分子模拟\ MD\ Club\ (Mr\_Materials) 欢迎关注公众号:分子模拟 MD Club (Mr_Materials)


关注 M r . m a t e r i a l   , \color{Violet} \rm Mr.material\ , Mr.material , 更 \color{red}{更} 多 \color{blue}{多} 精 \color{orange}{精} 彩 \color{green}{彩}

请添加图片描述

SCI论文绘图—Python绘图常用模板及技巧

数据的可视化展示,不仅是对数据的整理、思维逻辑的展示,更是一篇文章思想的表达和传递。现在很多文章喜欢用 Graph abstract 去展示文章的创新性和主要贡献。因此,绘图的技巧不仅包括:配色、符号以及数据信息的表达等,更要考虑文章的排版,整体的美观。同时,绘图的工具更是多样,Excel、Origin、Matlab等等。本专栏主要针对Python中的matplotlib,对绘图技巧,绘图风格进行说明。(注意:图片配色仅代表作者个人审美,程序提供仅编程思路)

案例讲解

本博文最后以此案例分析,并提供全部数据、代码。
在这里插入图片描述

请添加图片描述

前言:为什么要选择Python绘图?

注意:绘图过程涉及多个软件联合使用 , 包括: P y t h o n , P P T 以及 P h o t o s h o p 等 \color{red}{\rm 注意:绘图过程涉及多个软件联合使用,包括:Python,PPT 以及 Photoshop 等} 注意:绘图过程涉及多个软件联合使用,包括:PythonPPT以及Photoshop
绘图风格完全根据个人喜好,以及相关期刊风格。以下绘图模板只是提供参考。 \color{red}{\rm 绘图风格完全根据个人喜好,以及相关期刊风格。以下绘图模板只是提供参考。} 绘图风格完全根据个人喜好,以及相关期刊风格。以下绘图模板只是提供参考。
♠ \spadesuit 这里我们选择Python 和 origin两种绘图工具对比一下,数据都来自我之前的工作。都是两款优秀的绘图工具,但是我们明显可以看到,Python在细节和颜色的处理上更加细腻、丰富!
在这里插入图片描述
♠ \spadesuit ♠ \spadesuit 当然,这不足以作为选择Python的主要原因。
一个强大的开源包: p l t . s t y l e . u s e ( ‘ s c i e n c e ’ ) \rm plt.style.use(‘science’) plt.style.use(‘science’),可以绘制不同期刊风格(点击跳转
在这里插入图片描述
在这里插入图片描述
♠ \spadesuit ♠ \spadesuit ♠ \spadesuit 在处理相同数据图片的时候,这时我们只需要循环数据,就可以得到,方便简单。这里我用Jupyter Notebook 循环绘图了1000张数据结构相同的图片。
在这里插入图片描述

一、Python绘图基本工具

1. 图片初始生成 “前处理”——Jupyter notebook

所有的代码演示均采用 J u p y t e r   n o t e b o o k \rm Jupyter\ notebook Jupyter notebook 编写程序 (个人习惯),请根据自己使用习惯选择。
在这里插入图片描述

2. 图片处理的后期加工—PPT

在采用Python生成的图片之后,需要对图片进行,进一步的加工处理,包括对图片裁剪、组合等等。可以打开线条进行对齐等进一步加工。
在这里插入图片描述

3. 针对分子动力学的 Matlab 数据分析及 Python 绘图

这里主要针对之前的专栏内容《LAMMPS后处理以及编程技巧》,通过 M a t l a b \rm Matlab Matlab 对分子动力学的Dump轨迹进行分析,获得一维、二维矩阵,保存在 E x c e l \rm Excel Excel 进行 P y t h o n \rm Python Python 读取,绘图。
相关专刊请关注:
《LAMMPS后处理以及编程技巧》
《分子动力学后处理软件开发》

4. Python的参考

请根据绘图模板,结合手册的案例,制定自己的绘图风格。
请点击
在这里插入图片描述

二、Python绘图程序模板

1. 输出图片文件储存

import os
def make_save_file(filepath,filename,savename):
    # filepath 存储路径; 
    # filename:创建文件夹的名字 
    # savename:存储图片的名字
    
    save_path = filepath+os.sep+filename+os.sep+savename
    all_path  = filepath+os.sep+filename
    if not os.path.exists(all_path):
        os.mkdir(all_path)
    plt.savefig(save_path,dpi=1000)
filepath = r"图片路径"

font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 22,
             }
font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }

2. Excel文件读取

# 读取excel
excel_path = r"XXX.xlsx"
work_sheet = xlrd.open_workbook(excel_path);

# sheet的数量
sheet_num = work_sheet.nsheets;
# 获取sheet name
sheet_name = []

for sheet_num in range(1):  # 预留循环,用来循环画图,只有1个sheet就1
    # 选取sheet
    now_sheet = work_sheet.sheets()[0]  # 读取第几个sheet  
    # sheet的行
    row = now_sheet.nrows
    # sheet的列
    ncol = now_sheet.ncols

3. 图片格式子函数

def setup(ax,x_label,y_label):
    # 边框线的线宽设置
    width = 1.5
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['right'].set_linewidth(width)
    # 边框上的ticks的出现
    ax.tick_params(top='on', bottom='on', left='on', right='on', direction='in')
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad=9)
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.50, length=6)
    ax.tick_params(which='minor', width=0.75, length=0)
    # 边框上的ticks的出现的间隔
    locx = plticker.MultipleLocator(base=200) # this locator puts ticks at regular intervals
    ax.xaxis.set_major_locator(locx)
    locy = plticker.MultipleLocator(base=200) # this locator puts ticks at regular intervals
    #ax.yaxis.set_major_locator(locy)
    # 边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = x_label 
    yAxisLable = y_label
    ax.set_xlabel(xAxisLable, font1, labelpad=5)
    ax.set_ylabel(yAxisLable, font1, labelpad=5)

三、Python绘图模板-散点图、折线图、errorbar

1. 散点图、折线图

1. 核心命令

    p_1 = dict(marker='o',color = 'r',linestyle = '--',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    axe.plot(d_matrix, Parallel_matrix, **p_3)    

2. 散点图以及折线图

import os
def make_save_file(filepath,filename,savename):
    # filepath 存储路径; filename:创建文件夹的名字 savename:存储图片的名字
    save_path = filepath+os.sep+filename+os.sep+savename
    all_path  = filepath+os.sep+filename
    if not os.path.exists(all_path):
        os.mkdir(all_path)
    plt.savefig(save_path,dpi=1000)
filepath = r"test"
font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 18,
             }
font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }
# Global setting
# ----------------------------------------------------------------------#
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import optimize 
# coding:utf-8
import pylab
import matplotlib.ticker as plticker
from matplotlib.pyplot import MultipleLocator
import xlrd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
plt.style.use('science')
# ----------------------------------------------------------------------#
def setup(ax,x_label,y_label):
    # 边框线的线宽设置
    width = 1.5
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['right'].set_linewidth(width)
    # 边框上的ticks的出现
    ax.tick_params(top='on', bottom='on', left='on', right='on', direction='in')
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad = 6)
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2)
    # 边框上的ticks的出现的间隔
    locx = plticker.MultipleLocator(base=50) # this locator puts ticks at regular intervals
    ax.xaxis.set_major_locator(locx)
    locy = plticker.MultipleLocator(base=0.1) # this locator puts ticks at regular intervals
    ax.yaxis.set_major_locator(locy)
    # 边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = x_label 
    yAxisLable = y_label
    ax.set_xlabel(xAxisLable, font1, labelpad=5)
    ax.set_ylabel(yAxisLable, font1, labelpad=5)
# ----------------------------------------------------------------------#
# 读取excel
excel_path = r"test.xlsx"
work_sheet = xlrd.open_workbook(excel_path);

# sheet的数量
sheet_num = work_sheet.nsheets;
# 获取sheet name
sheet_name = []
for sheet in work_sheet.sheets():
    sheet_name.append(sheet.name)
# ----------------------------------------------------------------------#
# ----------------------------------------------------------------------#
for sheet_num in range(1):
    # 选取sheet
    fig, axe = plt.subplots(1, 1, figsize=(2.5, 5))
    now_sheet = work_sheet.sheets()[1]

    # sheet的行
    row = now_sheet.nrows
    # sheet的列
    ncol = now_sheet.ncols
    #----------------------------------------------------------------------#
    #----------------------------------------------------------------------#
    font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 18,
             }
    font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }
    d                 = now_sheet.col_values(0)
    d_matrix          = d[1:]  
    
    suiji                 = now_sheet.col_values(1)
    suiji_full_matrix     = suiji[1:]  
    
    suiji_solid                 = now_sheet.col_values(2)
    suiji_solid_full_matrix     = suiji_solid[1:]        
     
    suiji_gas                 = now_sheet.col_values(3)
    suiji_gas_full_matrix     = suiji_gas[1:]   
    
    suiji_couple                = now_sheet.col_values(4)
    suiji_couple_full_matrix      = suiji_couple[1:]   
    
    maxwell                = now_sheet.col_values(6)
    maxwell_matrix      = maxwell[1:]    
    
    Parallel                = now_sheet.col_values(7)
    Parallel_matrix      = Parallel[1:]    
    
    
    unit                = now_sheet.col_values(8)
    unit_matrix      = unit[1:]     
    #----------------------------------------------------------------------#
    #exp. from cai
    
    exp_dia = [13.59,20.31,28.64,34.61]
    exp_kappa =[0.02681,0.02723,0.02962,0.03176]

    #----------------------------------------------------------------------#
    elinewidth = 1
    alpha = 1
    capsize = 8
    markevery = 1
    markersize = 1
    #----------------------------------------------------------------------#
    p_s_1 =dict(marker='^',markersize=markersize,ecolor='r',color='r',\
                elinewidth=elinewidth, ls='none', alpha=alpha,capsize=capsize)
    p_s_2 =dict(marker='o',markersize=markersize,ecolor='g',color='g',\
                elinewidth=elinewidth, ls='none', alpha=alpha,capsize=capsize)
    p_s_3 =dict(marker='s',markersize=markersize,ecolor='b',color='b',\
                elinewidth=elinewidth, ls='none', alpha=alpha,capsize=capsize)
    p_s_4 =dict(marker='>',markersize=markersize,ecolor='c',color='c',\
                elinewidth=elinewidth, ls='none', alpha=alpha,capsize=capsize)
    p_s_5 =dict(marker='p',markersize=markersize,ecolor='m',color='m',\
                elinewidth=elinewidth, ls='none', alpha=alpha,capsize=capsize)
    
    markersize = 0                                          
    linewidth = 3
    markevery =1
    alpha =0.9 
    
    
    p_1 = dict(marker='o',color = 'r',linestyle = '--',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_2 = dict(marker='s',color = 'k',linestyle = '--',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_3 = dict(marker='<',color = 'g',linestyle = '--',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_4 = dict(marker='>',color = 'y',linestyle = '--',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_5 = dict(marker='o',color = 'm',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_6 = dict(marker='^',color = 'c',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_7 = dict(marker='p',color = 'r',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    markersize = 15
    p_s_8 =dict(marker='o',markersize=markersize,ecolor='r',color='none',mec='r',\
                elinewidth=elinewidth, ls='none', alpha=alpha,capsize=capsize)
       
    #----------------------------------------------------------------------#    
    markersize = 10
    
    axe.plot(d_matrix, suiji_full_matrix, **p_1)   
   
    axe.fill_between(np.arange(0,len(suiji_solid_full_matrix),1),suiji_full_matrix*np.array(0.85),suiji_full_matrix*np.array(1.2), 
                     alpha=0.03,color='r')      

    axe.plot(d_matrix, maxwell_matrix, **p_2)     
    
    axe.plot(d_matrix, Parallel_matrix, **p_3)     
     
    axe.plot(d_matrix, unit_matrix, **p_4)     
     
    
      
    axe.errorbar(exp_dia, exp_kappa, yerr=exp_kappa*np.array(0.09),  \
                **p_s_8,linestyle = 'none')   
    
    axe.legend(loc='best', frameon=False, labelspacing=0.3)
    axe.legend(bbox_to_anchor=(1.10, 1), loc='upper left', borderaxespad=0.,fontsize='x-large')
    axe.set_xlim(0,100)
    axe.set_ylim(0, 0.2)
    setup(axe,r'$\rm Diameter\ /nm$ ',r'$\rm \lambda_{e}\ /Wm^{-1}K^{-1}$') 
    # ============================================================#
    filename = "model"
    savename = "allmodel.jpg"    
    #make_save_file(filepath,filename,savename)

    # ----------------------------------------------------------------------#

plt.show()

3. 结果展示

在这里插入图片描述

2. Errorbar图

1. 核心命令

    x= np.array(1)*sin(np.array(0.01)*xx)
    y = np.array([3.14E-01,5.69E-01,7.60E-01,8.40E-01,9.80E-01,9.89E-01,1.00E+00])
    yerr = np.array([3.46E-02,3.68E-02,4.57E-02,6.38E-02,7.38E-02,5.38E-02,4.38E-02])
    axe.errorbar(x, y, yerr=yerr,**p_s_1,linestyle = 'none',label = r'MD,\ $\mu = 1 $')

2. 全部代码


# Global setting
# ----------------------------------------------------------------------#
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# coding:utf-8
import pylab
import matplotlib.ticker as plticker
from matplotlib.pyplot import MultipleLocator
import xlrd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import math
def func(x,beita_tar):
    return 0.022/(1+2*x*beita_tar)
font11 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 18,
             }
font22 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 24,
             }
plt.style.use('science')
# ----------------------------------------------------------------------#
def setup(ax,x_label,y_label):
    # 边框线的线宽设置
    width = 1.5
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['right'].set_linewidth(width)
    # 边框上的ticks的出现
    ax.tick_params(top='on', bottom='on', left='on', right='on', direction='in')
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad=7)
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.00, length=6)
    ax.tick_params(which='minor', width=0.75, length=2)
    # 边框上的ticks的出现的间隔
    locx = plticker.MultipleLocator(base=0.2) # this locator puts ticks at regular intervals
    ax.xaxis.set_major_locator(locx)
    locy = plticker.MultipleLocator(base=0.2) # this locator puts ticks at regular intervals
    ax.yaxis.set_major_locator(locy)
     #边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = x_label 
    yAxisLable = y_label
    ax.set_xlabel(xAxisLable, font11, labelpad=5)
    ax.set_ylabel(yAxisLable, font11, labelpad=5)
# ----------------------------------------------------------------------#
from pylab import *
from scipy.optimize import curve_fit
#linspace(0.46,0.5,10)
for LB in range(1): 
    xx = np.array([149,130,108,56,35,30,12])
    #xx = np.array([12,30,35,46,108,130,149])
    #x = np.array([0.006711409,0.007692308,0.009259259,0.02173913,0.028571429,0.033333333
    #,0.083333333])*np.array(100)

    #x= np.array(1)*cos(np.array(0.01)*xx)  LB*np.exp(-1/b*(2*x))+LB
    x= np.array(1)*sin(np.array(0.01)*xx)
    y = np.array([3.14E-01,5.69E-01,7.60E-01,8.40E-01,9.80E-01,9.89E-01,1.00E+00])
    
    
    yerr = np.array([3.46E-02,3.68E-02,4.57E-02,6.38E-02,7.38E-02,5.38E-02,4.38E-02])

    markersize = 10  
    linewidth = 1.5


    p_s_1 =dict(marker='o',markersize=markersize,ecolor='r',color='r',\
                elinewidth=0.5, ls='none', alpha=1,capsize=5)
    fig, axe = plt.subplots(1, 1, figsize=(5,5))
    axe.errorbar(x, y, yerr=yerr,**p_s_1,linestyle = 'none',label = r'MD,\ $\mu = 1 $')

    x=linspace(0,20,1000)
    plot(x,1-0.5153*np.array(x**2),color='r',ls='--',label='fitting')


    y_fit_low_matrix   = 1-0.3604*np.array(x**2)
    y_fit_high_matrix  = 1-0.6703*np.array(x**2)
    
    #1-np.exp(-b*(x))
    axe.fill_between(linspace(0,20,1000),y_fit_low_matrix, y_fit_high_matrix, alpha=0.1,color='r',label='Reference values range')
    
    
   
    axe.set_xlim(0,1.2)
    axe.set_ylim(0.2, 1)
    #axe.set_xlim(0, 5)
    setup(axe,r'$\rm \sin(0.01  {\rm \theta})$',r'$\rm \alpha$')
    #axe.errorbar(x1_matrix, y1_matrix, yerr=y1_matrix_err,**p_s_1,linestyle = 'none',label = 'MD')
    # np.array(15)*cos(np.array(0.009)*xx)

    axe.legend(loc='best', frameon=False, \
                      labelspacing=0.3)
    axe.legend(bbox_to_anchor=(1.10, 1), \
                      loc='upper left', borderaxespad=0.,fontsize='x-large')
    filename = "1"
    savename = "1.pdf"
    #make_save_file(filepath,filename,savename)
    show()

3. 报道结果

在这里插入图片描述

3. 双Y轴图

1.核心命令

    axe1 = axe.twinx()
    axe1.plot(y10nm_time_matrix,y10nm_temp_matrix,**p_2,label='10 nm')    

2.全部代码

font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 22,
             }
font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# coding:utf-8
import pylab
import matplotlib.ticker as plticker
from matplotlib.pyplot import MultipleLocator
import xlrd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
slope = []
plt.style.use('science')
# ----------------------------------------------------------------------#
def setup(ax,xlabel,ylabel,color):
    # 边框线的线宽设置
    width = 2
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['left'].set_color(color)
    
    ax.spines['right'].set_linewidth(width)
    ax.spines['right'].set_visible(False)
    # 边框上的ticks的出现
    ax.tick_params(top='on', bottom='on', left='on', right='off', direction='in')
    ax.tick_params(axis='y',which ='both', labelcolor=color,color = color)
    
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad=6.5)
        
    ax.tick_params(which='major', width=1.00, length=6)
    ax.tick_params(which='minor', width=0.75, length=0)
    
    # 边框上的ticks的出现的间隔
    #locx = plticker.MultipleLocator(base=38) # this locator puts ticks at regular intervals
    #ax.xaxis.set_major_locator(locx)
    #locy = plticker.MultipleLocator(base=20) # this locator puts ticks at regular intervals
    #ax.yaxis.set_major_locator(locy)
    # 边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = xlabel
    yAxisLable = ylabel
    ax.set_xlabel(xAxisLable, font1, labelpad=5,color ='k')
    ax.set_ylabel(yAxisLable, font1, labelpad=5,color =color)
def setup_r(ax,xlabel,ylabel,color):
    width = 2
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    
    ax.spines['left'].set_linewidth(width)
    ax.spines['left'].set_visible(False)
    
    ax.spines['right'].set_linewidth(width)
    ax.spines['right'].set_color(color)
    ax.tick_params(labelsize=20,pad =6.5)
    # 边框上的ticks的出现
    ax.tick_params(top='off', bottom='off', left='off', right='on', direction='in')
    ax.tick_params(axis='y',which ='both', labelcolor=color,color = color)
    #locy = plticker.MultipleLocator(base=max[num]*np.array(1000)/2) # this locator puts ticks at regular intervals
    #ax.yaxis.set_major_locator(locy)
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20)
        
    ax.tick_params(which='major', width=1.50, length=6)
    ax.tick_params(which='minor', width=0.75, length=0)
    # 边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = xlabel
    yAxisLable = ylabel
    ax.set_xlabel(xAxisLable, font1, labelpad=5,color =color)
    ax.set_ylabel(yAxisLable, font1, labelpad=6,color =color)

# ----------------------------------------------------------------------#
# 读取excel
excel_path = r"1.xlsx"
work_sheet = xlrd.open_workbook(excel_path);

# sheet的数量
sheet_num = work_sheet.nsheets;
# 获取sheet name
sheet_name = []
all_k =[]
all_2 =[]
for sheet in work_sheet.sheets():
    sheet_name.append(sheet.name)
# ----------------------------------------------------------------------#
# ----------------------------------------------------------------------#
for num in range(1):
    # 选取sheet    
    now_sheet = work_sheet.sheets()[3]  
    #----------------------------------------------------------------------#
    y10nm_time        = now_sheet.col_values(1)
    y10nm_time_matrix = y10nm_time[1:]
    
    y10nm_Q6        = now_sheet.col_values(2)
    y10nm_matrix    = y10nm_Q6[1:]

    y10nm_temp        = now_sheet.col_values(3)
    y10nm_temp_matrix = y10nm_temp[1:]     
    #----------------------------------------------------------------------#    
    
    linewidth = 2
    #fig = plt.figure()
    fig, axe = plt.subplots(1, 1, figsize=(5, 5))
    #axe = fig.add_axes([0, 0,1, 1])

    markersize = 10  
    linewidth = 1
    markevery =1
    alpha =0.3
    p_1 = dict(marker='o',color = 'r',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_2 = dict(marker='s',color = 'b',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)

   
    alpha=1
    linewidth = 2
    
    ax = plt.gca()
    

    #--------------------------------------------------------------------------------------------------#
    name = "Temperature "#+"      "+str(y1_name)
    ax = plt.gca()
    linewidth=2.
    
    axe.plot(y10nm_time_matrix,y10nm_matrix,**p_1,label='10 nm')

    
    axe.set_xlim(0, 1000)
    #axe.set_ylim(y_min, y_max)

    axe1 = axe.twinx()
    #axe1.set_ylim(0, 0.006*np.array(1000))
    #axe1.set_ylim(0, 0.0075)

    axe1.plot(y10nm_time_matrix,y10nm_temp_matrix,**p_2,label='10 nm')    
    
    setup(axe,r'z /$\rm \AA$',r'Temperature /$\rm K$','r')
    setup_r(axe1,r'1',r'Number density /$10^{-3}$$\rm \AA^{-3}$','b')
    axe.legend(loc='best', frameon=False, labelspacing=0.3)
    axe1.legend(loc='best', frameon=False, labelspacing=0.3)
    axe.legend(bbox_to_anchor=(1.4, 1), loc='upper left', borderaxespad=0.,fontsize='x-large')
    axe1.legend(bbox_to_anchor=(1.4,0.85), loc='upper left', borderaxespad=0.,fontsize='x-large')
    #--------------------------------------------------------------------------------------------------#
    # ============================================================#
    #figureFileName = "Amorphous_overlop.pdf"
    #figureFileName = name+'-> '+str(y1_num_name)
    filename = "pic5"
    savename = "1.8.pdf"
    #make_save_file(filepath,filename,savename)
    #print(figureFileName)
    #plt.savefig(figureFileName, dpi=300)
    # plt.xscale("log")
    #plt.yscale("log")
    # ----------------------------------------------------------------------#
    plt.show()

在这里插入图片描述

4. Bar图

这里计算结果对比了集中热导率的计算方法,请参考博文《漫谈分子动力学计算热导率的五种方法》

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
import numpy as np
# coding:utf-8
import pylab
import matplotlib.ticker as plticker
from matplotlib.pyplot import MultipleLocator
import xlrd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
plt.style.use('science')

def setup(ax):
    # 边框线的线宽设置
    width = 1.5
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['right'].set_linewidth(width)
    # 边框上的ticks的出现
    ax.tick_params(top='off', bottom='on', left='on', right='off', direction='in')
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad = 6)
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.50, length=6)
    ax.tick_params(which='minor', width=0., length=2)
    plt.xticks(rotation=-30)
    # 边框上的ticks的出现的间隔
    #locx = plticker.MultipleLocator(base=0.5) # this locator puts ticks at regular intervals
    #ax.xaxis.set_major_locator(locx)

    locy = plticker.MultipleLocator(base=0.2) # this locator puts ticks at regular intervals
    ax.yaxis.set_major_locator(locy)
     #边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离


fig, axe = plt.subplots(1, 1, figsize=(6, 5))   
labels = ['Fix ehex', 'Fix Langvein', 'Fix heat','EMD','MP']


ehex = [0.2391]
ehex_error = [0.0069]
    
langvein = [0.2667]
langvein_error = [0.0004925]
    
heat = [0.2524]
heat_error = [0.010419]    
    
emd = [0.30]
emd_error = [0.02]   

mp = [0.26]
mp_error = [0.005]  


x = np.arange(len(labels))  # the label locations
width = 0.7  # the width of the bars


ehex = axe.bar(width/2 ,ehex, width,yerr=ehex_error,capsize=5,ecolor='r',\
            facecolor='b',edgecolor='k',label='Tersoff(2007)',alpha=0.5,hatch='//')

langvein = axe.bar(1+width/2 ,langvein, width, yerr=langvein_error,capsize=5,ecolor='r',\
            facecolor='c',edgecolor='k',label='Vashishta(1990)',alpha=0.5,hatch='\\\\')

heat = axe.bar(2+width/2 ,heat, width, yerr=heat_error,capsize=5,ecolor='r',\
            facecolor='c',edgecolor='k',label='Vashishta(1997)',alpha=0.5,hatch='\\')

emd = axe.bar(3+width/2 ,emd, width, yerr=emd_error,capsize=5,ecolor='r',\
            facecolor='y',edgecolor='k',label='BKS\_LJ(cutoff 2.5)',alpha=0.5,hatch='-')

mp = axe.bar(4+width/2 ,mp, width, yerr=mp_error,capsize=5,ecolor='r',\
            facecolor='y',edgecolor='k',label='Only BKS',alpha=0.5,hatch='--')


axe.set_xticks(x+0.5*np.array(width))
axe.set_xticklabels(labels,font1)

axe.set_ylabel(r'$\rm Thermal\ conductivity\ /Wm^{-1}K^{-1}$', font1, labelpad=5)
#axe.set_xlim(0,5)
axe.set_ylim(0,0.4)

fig.tight_layout()
setup(axe)

filename = "BAR"
savename = "BAR4.jpg"
make_save_file(filepath,filename,savename)

plt.show()

请添加图片描述

5. Python 动画绘制思路

GIF图片的制作过程分为两步,第一步是绘制保存不同时刻的图片,第二步将PNG等类型图片绘制成GIF。

1. 绘制保存不同时刻图片

这一步也决定了这个动画要做多少帧。简单举例,假如我们有1000行数据,我每增加100行数据做一个图片,那么做出来的图片数也就是10,GIF图片帧数也就是10,若每10行数据做一个图片,那么总帧数100,这个过程的实现依据一个循环来实现,代码如下。plot中x,y的参数中sheet_num*10为每次循环增加10行参数进行绘图,plt.axvline用来绘制垂直于X方向的辅助线。

在这里需要注意, 我们需要简单计算一下循环次数,次数少则图片少,GIF动画不全;次数多则超出范围报错,影响我们接下来制作GIF的操作,当然也可以使用一些软件来制作GIF来壁面这个问题。

for sheet_num in range(250):                                #循环次数=输出图片个数,需要计算一下        
    now_sheet = work_sheet.sheets()[0]  #第一个表
    row = now_sheet.nrows                                   # 获得sheet的行数
    ncol = now_sheet.ncols                                  # 获得sheet的列数
    
    temp = now_sheet.col_values(2)
    y_temp =  list(filter(None, temp[1:]))                  # 获取y temperature
    
    time = now_sheet.col_values(0)
    x_time = list(filter(None, time[1:]))                   # 获取x time
    
    #----------------------------------------------------------------------#    
    fig, axe = plt.subplots(1, 1, figsize=(8,5))            
    
    markersize = 8                                         
    linewidth = 2
    markevery =1
    alpha =0.9 
    
    p_1 = dict(marker='o',color = 'b',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_2 = dict(marker='s',color = 'k',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_3 = dict(marker='<',color = 'g',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_4 = dict(marker='>',color = 'y',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_5 = dict(marker='o',color = 'm',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_6 = dict(marker='^',color = 'c',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_7 = dict(marker='p',color = 'r',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
        
    p_11 = dict(color = 'r',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_22 = dict(color = 'b',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_33 = dict(color = 'g',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_44 = dict(color = 'y',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_55 = dict(color = 'm',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_66 = dict(color = 'c',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_77 = dict(color = 'r',linestyle = '--',linewidth=linewidth,alpha=alpha)  
    
    
    #axe.plot(x_time, y_temp,**p_1,label='Temperature')
    axe.plot(x_time[0:sheet_num*10], y_temp[0:sheet_num*10], **p_1,label='Temperature')    #每次增加100个点
    plt.axvline(x_time[sheet_num*10],color='k',lw=2,linestyle='dashed')

2. 制作GIF图像

可以将GIF图片保存后使用相关软件或网站制作,也可以使用PYTHON的imageio包制作,这里给出使用imageio制作的代码。duration参数是每一帧的持续时间,默认为1s,根据需求进行更改。

# GIF生成
import imageio
import glob
import re

outfilename = "Temperature_change.gif" 
pic_names = sorted(glob.glob('./pic_outfile/*.jpg'),key=lambda x: int(re.findall("[0-9]+", x)[0]))

frames = []
for image_name in pic_names:                                                   
    im = imageio.imread(image_name)
    frames.append(im)         
imageio.mimsave(outfilename, frames, 'GIF', duration=1) 

3. 绘制效果展示

请添加图片描述
请添加图片描述
请添加图片描述

4. 文件下载

上第一个 G I F 图全部代码及 e x c e l 文件 \rm 上第一个GIF图全部代码及excel文件 上第一个GIF图全部代码及excel文件

excel文件,提取码:ojcb
全部代码如下:

# -*- coding: utf-8 -*-
"""
Created on Jan  16 16:21:18 2022

@author: 努力的阿磊啊

describe:Temperature change
"""

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pylab
import matplotlib.ticker as plticker
from matplotlib.pyplot import MultipleLocator
import xlrd
from matplotlib.lines import Line2D
import math
from scipy import optimize       
plt.style.use('science')

# ----------------------------------------------------------------------#
# 先定义输出的文件夹
import os
def make_save_file(filepath,filename,savename):
    # filepath 存储路径; filename:创建文件夹的名字 savename:存储图片的名字
    save_path = filepath+os.sep+filename+os.sep+savename
    all_path  = filepath+os.sep+filename
    if not os.path.exists(all_path):
        os.mkdir(all_path)
    plt.savefig(save_path,dpi=150)
filepath = r"C:\Users\Lenlovo\Desktop\数据处理结果\弛豫温度变化"             
font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 18,
             }
font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }

# ----------------------------------------------------------------------#
# 绘图函数
def setup(ax,x_label,y_label):
    # 边框线的线宽设置
   
    font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 18,
             }
    font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }
    
    width = 1.5   
    ax.spines['top'].set_linewidth(width)       #设置上边框线粗1.5   
    ax.spines['bottom'].set_linewidth(width)    #设置下边框线粗1.5  
    ax.spines['left'].set_linewidth(width)      #设置左边框线粗1.5  
    ax.spines['right'].set_linewidth(width)     #设置右边框线粗1.5  
    # 边框上的刻度的出现
    ax.tick_params(top='on', bottom='on', left='on', right='on', direction='in')  #四个边框线都设有刻度,方向朝内
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad=6)                       # 标签间距为20,刻度与标签间距离为6
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.50, length=6)      #主刻度线设置
    ax.tick_params(which='minor', width=0.75, length=0)      #副刻度线设置
    # 边框上的ticks的出现的间隔
    locx = plticker.MultipleLocator(base=2.5)                 # X间距2.5
    ax.xaxis.set_major_locator(locx)
    locy = plticker.MultipleLocator(base=100)                 # Y间距100
    ax.yaxis.set_major_locator(locy)
    # 边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = x_label 
    yAxisLable = y_label
    ax.set_xlabel(xAxisLable, font1, labelpad=5)             #font1 是额外的设置
    ax.set_ylabel(yAxisLable, font1, labelpad=5)
    
    
    
# ----------------------------------------------------------------------#
# 读取excel
excel_path = r"Temperature_change.xlsx"                                        
work_sheet = xlrd.open_workbook(excel_path);  
# sheet的数量
sheet_num = work_sheet.nsheets;
# 获取sheet name
sheet_name = []


for sheet_num in range(250):                                #循环次数=输出图片个数,需要计算一下        
    # 选取sheet;读取哪个工作表
    now_sheet = work_sheet.sheets()[0]  #第一个表
    # sheet的行
    row = now_sheet.nrows                                   # 获得sheet的行数
    # sheet的列
    ncol = now_sheet.ncols                                  # 获得sheet的列数
    
    temp = now_sheet.col_values(2)
    y_temp =  list(filter(None, temp[1:]))                  # 获取y temperature
    
    time = now_sheet.col_values(0)
    x_time = list(filter(None, time[1:]))                   # 获取x time
    
    #----------------------------------------------------------------------#    
    fig, axe = plt.subplots(1, 1, figsize=(8,5))            
    
    markersize = 8                                          
    linewidth = 2
    markevery =1
    alpha =0.9 
    
    p_1 = dict(marker='o',color = 'b',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_2 = dict(marker='s',color = 'k',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_3 = dict(marker='<',color = 'g',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_4 = dict(marker='>',color = 'y',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_5 = dict(marker='o',color = 'm',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_6 = dict(marker='^',color = 'c',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
    p_7 = dict(marker='p',color = 'r',linestyle = 'none',markevery=markevery,markerfacecolor='none',markersize=markersize,linewidth=linewidth,alpha=alpha)
        
    p_11 = dict(color = 'r',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_22 = dict(color = 'b',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_33 = dict(color = 'g',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_44 = dict(color = 'y',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_55 = dict(color = 'm',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_66 = dict(color = 'c',linestyle = '--',linewidth=linewidth,alpha=alpha)
    p_77 = dict(color = 'r',linestyle = '--',linewidth=linewidth,alpha=alpha)  
    
    
    #axe.plot(x_time, y_temp,**p_1,label='Temperature')
    axe.plot(x_time[0:sheet_num*10], y_temp[0:sheet_num*10], **p_1,label='Temperature')    #每次增加100个点
    plt.axvline(x_time[sheet_num*10],color='k',lw=2,linestyle='dashed')
    
    #细节绘制
    axe.set_ylim(250, 750)
    axe.set_xlim(-0.1, 12.5)
    setup(axe,r'$\rm Time\ /ns$',r'$\rm Temperature\ /K$')
    axe.legend(loc='upper right', frameon=False, \
                  labelspacing=0.3,fontsize='xx-large')
    #axe.legend(bbox_to_anchor=(1.10, 1), \
                  #loc='upper left', borderaxespad=0,fontsize='xx-large')

    # 图片保存
    filename = "pic_outfile"
    savename = str(sheet_num)+".jpg"
    make_save_file(filepath,filename,savename)

    #plt.savefig(figureFileName, dpi=300)
    # 
    # ----------------------------------------------------------------------#

# ----------------------------------------------------------------------#
# GIF生成
import imageio
import glob
import re

outfilename = "Temperature_change.gif" 
pic_names = sorted(glob.glob('./pic_outfile/*.jpg'),key=lambda x: int(re.findall("[0-9]+", x)[0]))

frames = []
for image_name in pic_names:                                                   
    im = imageio.imread(image_name)
    frames.append(im)         
imageio.mimsave(outfilename, frames, 'GIF', duration=1) 

四、Python绘图模板-二维云图(针对于分子模拟)

1. 根据三列数据绘制云图

1. 数据结构

在这里插入图片描述

2. 全部程序

# Global setting
#----------------------------------------------------------------------#
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.ticker as ticker
#coding:utf-8
import pylab
import matplotlib.ticker as plticker
import xlrd
from mpl_toolkits.mplot3d import Axes3D
from scipy.interpolate import griddata
plt.style.use('science')
#----------------------------------------------------------------------#
#----------------------------------------------------------------------#
def excel_to_matrix(path):
    table = xlrd.open_workbook(path).sheets()[sheet]
    row = table.nrows
    col = table.ncols
    datamatrix = np.zeros((row, col))
    for x in range(col):
        cols = np.matrix(table.col_values(x))
        datamatrix[:, x] = cols
    return datamatrix
#A = excel_to_matrix('20_1.xlsx')
# ----------------------------------------------------------------------#
def setup(ax,x_label,y_label):
    # 边框线的线宽设置
    width = 1.5
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['right'].set_linewidth(width)
    # 边框上的ticks的出现
    ax.tick_params(top='on', bottom='on', left='on', right='on', direction='in')
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad=6)
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2)
    # 边框上的ticks的出现的间隔
    locx = plticker.MultipleLocator(base=15) # this locator puts ticks at regular intervals
    ax.xaxis.set_major_locator(locx)
    locy = plticker.MultipleLocator(base=15) # this locator puts ticks at regular intervals
    ax.yaxis.set_major_locator(locy)
     #边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = x_label 
    yAxisLable = y_label
    ax.set_xlabel(xAxisLable, font11, labelpad=5)
    ax.set_ylabel(yAxisLable, font11, labelpad=5)
# ----------------------------------------------------------------------#
# 读取excel
excel_path = r"test.xlsx"
work_sheet = xlrd.open_workbook(excel_path);

# sheet的数量
sheet_num  = work_sheet.nsheets;

# 选取sheet
now_sheet  = work_sheet.sheets()[2]

# sheet的行
row        = now_sheet.nrows
# sheet的列
ncol       = now_sheet.ncols
fig = plt.figure()
# 获取第行内容
#rows_select = now_sheet.row_values(1)
#rows_now    = table.row_values(rows_now, start_colx=0, end_colx=None)
# 循环所有的列
for i in range(1):

    # 获取第列内容 np.linspace(start = 0, stop = 100, num = 5)
    #ax = Axes3D(fig)
    #x,y= np.meshgrid(now_sheet.col_values(0),now_sheet.col_values(1))
    #y = np.meshgrid(now_sheet.col_values(1))
    #z = np.meshgrid(now_sheet.col_values(2),now_sheet.col_values(2))[0]
    x = now_sheet.col_values(0)
    y = now_sheet.col_values(1)
    values = now_sheet.col_values(3)
    color = now_sheet.col_values(3)
    #print(values)
    #ax.plot_trisurf(x, y, plate, alpha=0.3,cmap=plt.get_cmap('rainbow'))
    #ax.plot_trisurf(x, y, values, alpha=0.7,cmap = plt.get_cmap('rainbow'))
    points = np.array([x, y])
    xx = np.linspace(start=np.array(x).min(), stop=np.array(x).max(), num=50)
    yy = np.linspace(start=np.array(y).min(), stop=np.array(y).max(), num=50)
    X, Y = np.meshgrid(xx, yy)
    znew = griddata(points.T, values, (X, Y))  # 进行插值
    newcolor = griddata(points.T, values, (X, Y))  # 进行插值
    plate_new = griddata(points.T, color, (X, Y))  # 进行插值
    
    fig, axe = plt.subplots(1, 1, figsize=(5,5))
    #axe = Axes3D(fig)
    #axe.plot_surface(X, Y, znew, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))#cmap=plt.get_cmap('rainbow')
    #axe.contourf(X, Y, znew,origin='upper',cmap='rainbow',vmin = 0.01,vmax =0.05)
    #axe.plot_trisurf(x, y, plate, alpha=0.3, cmap=plt.get_cmap('rainbow'))
    levels = np.arange(125,170,2)
    levels_now = np.arange(125,170,0.5)
    cm = plt.cm.get_cmap('rainbow',len(levels_now))
    cs=axe.contourf(X, Y, znew, origin='upper',cmap='rainbow',vmin = 125,vmax =170,levels=levels_now)
    
    cbar = fig.colorbar(cs,format='%.0f')
    #cbar.outline.set_color('block')
    cbar.outline.set_linewidth(1.5)
    cbar.ax.tick_params(labelsize=14)
    width = 1.5
    

    setup(axe,r"$w(\rm \AA )$",r"s(\rm \AA )")
    #----------------------------------------------------------------------#
    font1 = {'family' : 'Times New Roman',
    'weight' : 'bold',
    'size'   : 13,
    }
    font2 = {'family' : 'Times New Roman',
    'weight' : 'normal',
    'size'   : 11,
    }
    #ax = Axes3D(fig)
    #plt.contourf(z,cmap='rainbow')
    #ax.plot_surface(z,origin='upper',cmap='rainbow')
    #plt.plot_surface(X,Y,Z,alpha=0.3,cmap='winter')
    # # correction of data, this must be done with reasons explained clearly.
    # x1=np.array(x1)+273
    # y2=np.array(y1)*1.1

    #============================================================ indication of Case
    plotTitle=""
    # please choose long or short as that shown in title, if necessary
    figureFileName="figure.pdf"

    '''name of axis and its units'''
    xAxisLable = r'X'#r' z/ $\rm \AA$'
    xComment=''
    yAxisLable = r'Y'#r'Number density ${\rm \AA}_{-3}$'
    # $\text{Wm^{-1}K^{-2}}$
    yComment=''
    #细节调整
    #----------------------------------------------------------------------#
    # plt.xscale("log")
    # plt.yscale("log")
    plt.xlim((5,45))
    plt.ylim((25,70))
    #plt.ylim((0.8*np.array(col_matrix).min(),1.2*np.array(col_matrix).max()))
    plt.legend(loc='best', frameon=False, labelspacing=0.3)
    #============================================================ frames, axis and labels

    filename = "out"
    savename = "1.jpg"
    make_save_file(filepath,filename,savename)
    plt.show()

3. 报道结果

在这里插入图片描述

2. 根据二维矩阵绘制云图

1. 数据结构—二维矩阵

在这里插入图片描述

2. 核心命令—读取矩阵

    def excel_to_matrix(excel_path):
        table = xlrd.open_workbook(excel_path).sheets()[sheet_num*4]
        row   = table.nrows                              
        col    = table.ncols                              
        datamatrix = np.zeros((row, col))            
        for x in range(col):
            cols = np.matrix(table.col_values(x))    
            datamatrix[:, x] = cols                      
        return datamatrix
    
    A = excel_to_matrix(excel_path)

3. 全部程序

# Global setting
# ----------------------------------------------------------------------#
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# coding:utf-8
import pylab
import matplotlib.ticker as plticker
from matplotlib.pyplot import MultipleLocator
import xlrd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import math
from scipy import optimize
import numpy as np
import pandas as pd
import xlrd
from sklearn import preprocessing
from skimage import transform
import pylab as plt
import matplotlib as mpl
import os
from matplotlib import ticker


from scipy import optimize
plt.style.use('science')
# ----------------------------------------------------------------------#
# ----------------------------------------------------------------------#
def setup(ax,x_label,y_label):
    # 边框线的线宽设置
    width = 1.5
    ax.spines['top'].set_linewidth(width)
    ax.spines['bottom'].set_linewidth(width)
    ax.spines['left'].set_linewidth(width)
    ax.spines['right'].set_linewidth(width)
    # 边框上的ticks的出现
    ax.tick_params(top='on', bottom='on', left='on', right='on', direction='in')
    # 边框上的ticks对应的lable,即数字的尺寸
    ax.tick_params(labelsize=20,pad=6)
    #ax.yaxis.set_ticks_position('right')
    ax.tick_params(which='major', width=1.50, length=6)
    ax.tick_params(which='minor', width=0.75, length=0)
    # 边框上的ticks的出现的间隔
    locx = plticker.MultipleLocator(base=100000) # this locator puts ticks at regular intervals
    ax.xaxis.set_major_locator(locx)
    locy = plticker.MultipleLocator(base=100000) # this locator puts ticks at regular intervals
    ax.yaxis.set_major_locator(locy)
    # 边框上的注释labels
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    # 边框上的注释labels距离坐标轴的距离
    xAxisLable = x_label 
    yAxisLable = y_label
    #ax.set_xlabel(xAxisLable, font1, labelpad=5)
    #ax.set_ylabel(yAxisLable, font1, labelpad=5)
# ----------------------------------------------------------------------#
# 读取excel
filename = "out"
excel_path = r"test.xls"
work_sheet = xlrd.open_workbook(excel_path);

# sheet的数量
sheet_num = work_sheet.nsheets;
# 获取sheet name
sheet_name = []

for sheet in work_sheet.sheets():
    sheet_name.append(sheet.name)
# ----------------------------------------------------------------------#
# ----------------------------------------------------------------------#
for sheet_num in range(1):
    #----------------------------------------------------------------------# 
    font1 = {'family': 'Times New Roman',
             'weight': 'bold',
             'size': 18,
             }
    font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 11,
             }
    #----------------------------------------------------------------------#
    def excel_to_matrix(excel_path):
        table = xlrd.open_workbook(excel_path).sheets()[sheet_num*4]
        row   = table.nrows                              
        col    = table.ncols                              
        datamatrix = np.zeros((row, col))            
        for x in range(col):
            cols = np.matrix(table.col_values(x))    
            datamatrix[:, x] = cols                      
        return datamatrix
    
    A = excel_to_matrix(excel_path)
    
    
    fig, axe = plt.subplots(1, 1, figsize=(3,3))
    xxx = np.arange(10000)

    levels = np.arange(0.0,0.15,0.005)    
    
    mag=2
    pic_resize_transform = transform.resize(A, (1000,1000),order=3) 
   
    cm = plt.cm.get_cmap('rainbow',len(levels))
    # levels=levels
    sc = axe.contourf(pic_resize_transform,origin='upper',cmap='rainbow',vmin=0.00,vmax=0.1,levels=levels)
       
    #plt.colorbar(sc)
    
    # vmin = 0.001,vmax =0.005
    #----------------------------------------------------------------------#        
    #plt.yscale("log")
    axe.set_ylim(350,750)
    axe.set_xlim(450, 750)
    # 0.0290---x 
    # 0.030.3---y
    plt.xticks( [450,750],\
               ['13','22'])
    plt.yticks( [350,750],\
                ['10','22'])  
    
    
    #setup(axe,r'$\rm X\ /\AA$',r'$\rm Y\ /\AA$')
    setup(axe,r'$\rm X\ /\AA$',r'$\rm Y\ /\AA$')   
    axe.legend(loc='best', frameon=False, \
                  labelspacing=0.3)
    axe.legend(bbox_to_anchor=(1.10, 1), \
                  loc='upper left', borderaxespad=0.,fontsize='xx-large')
    
    #axe[1].legend(loc='best', frameon=False, labelspacing=0.3)
    #axe[1].legend(bbox_to_anchor=(1.10, 1), loc='upper left', borderaxespad=0.,fontsize='x-large')
    # ============================================================#
    #plt.xscale("log")

   
    savename = str(sheet_num)+".jpg"
    #str(sheet_num)
    make_save_file(filepath,filename,savename)
    #figureFileName = "Amorphous_overlop.pdf"
    figureFileName = "Jump_temp.pdf"

    #plt.savefig(figureFileName, dpi=300)
    # ----------------------------------------------------------------------#

    plt.show()

在这里插入图片描述

五、案例讲解

1、数据结构

在这里插入图片描述

2、全部文件代码下载

链接:请点击
提取码:msn8

  • 19
    点赞
  • 90
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr. Material

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值