python科研绘图(表格+折线图)

这个例子是读取castep文件数据进行的绘图,使用python的绘图的优点在于可以利用循环,自动化批量处理数据,避免了人为重复性操作,降低出错率,实现自动绘图,通过遍历目标文件夹,检索目标数据,
收集并且绘图,另外python拥有丰富的第三方库,这个例子主要使用了matplotlib库进行绘图,python版本为3.10,编辑器为jupyter notebook,具体代码如下:

import matplotlib.pyplot as plt
import os
import pandas as pd
from matplotlib.ticker import MaxNLocator
y1 = []
x1 = []
y2 = []
y11 = []
y3 = []
data = {}


def traverse_folder(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            # 打开文件
            ft = os.path.join(root, file)
            
            if ft[-6:] == "castep":
                with open(ft, 'r') as f:
                    text = f.readlines()  # 读取目标文件内容
                    for line in text:
                        if "cut-off energy for mixing" in line:
                            tag = line.strip().split(':')[1].split()[0]
                            
                            if tag[:3] in ft:
                                x1.append(tag)
                                with open(ft, 'r') as l:
                                    text = l.readlines()  # 读取目标文件内容
                                    for i in text:
                                        if "Final Enthalpy" in i:
                                            data2 = i.strip().split('=')[1]
                                            y1.append(eval(data2[:-3])/18)
                                            y11.append(eval(data2[:-3]))

                                        if 'Total time' in i:
                                            data1 = i.strip().split('=')[1].strip()
                                            y2.append(eval(data1[:-1]))

    return x1, y1, y2


def y3c():
    for i in range(len(y1)):
        if i == 0:
            y3.append(i)
        else:
            y3.append(y1[i] - y1[i-1])
    data['Encut/eV'] = x1
    data['System energy/eV'] = y11
    data['Average atomic energy/eV'] = y1
    data['Relative energy/eV'] = y3
    data['Calculation time/s'] = y2

    return y3, data


def tabledraw(data, path_to_save, dpi=300, figsize=(10, 6), fontsize=14):
    # 创建一个简单的DataFrame(表格)
    df = pd.DataFrame(data)

    # 绘制表格
    fig, ax = plt.subplots(figsize=figsize)  # 增大绘图窗口大小
    ax.axis('off')  # 隐藏坐标轴

    # 设置表格的位置和列标签
    the_table = ax.table(cellText=df.values, colLabels=df.columns, loc='center', cellLoc='center')

    # 调整单元格间距和字体大小
    the_table.set_fontsize(fontsize)
    the_table.scale(1, 2)  # 增大垂直方向上的缩放因子,使表格更高

    # 隐藏坐标轴外的空白
    plt.tight_layout()

    # 保存图片
    plt.savefig(path_to_save + "/表格1.png", dpi=dpi, bbox_inches='tight')

    # 显示图片
    plt.show()


def plot_1(path_to_save, x, y1, y2):
    fig, ax1 = plt.subplots(figsize=(20, 10), dpi=100)

    # 设置第一个y轴的属性
    ax1.set_xlabel("Encut")
    ax1.set_ylabel("Average atomic energy/eV", color='b')
    ax1.tick_params('y', colors='b')
    ax1.grid(visible=True, which='major', linestyle='-', color='b', alpha=0.5)
    ax1.grid(visible=True, which='minor', linestyle='--', color='b', alpha=0.2)
    ax1.minorticks_on()
    ax1.plot(x, y1, '-o', color="b", label='Energy', linewidth=1)

    # 创建第二个y轴
    ax2 = ax1.twinx()

    # 设置第二个y轴的属性
    ax2.set_ylabel("Calculation time/s", color='r')
    ax2.tick_params('y', colors='r')
    ax2.grid(visible=True, which='major', linestyle='-', color='r', alpha=0.5)
    ax2.grid(visible=True, which='minor', linestyle='--', color='r', alpha=0.2)
    ax2.plot(x, y2, '-v', color="r", label='time', linewidth=1)
    y2_min, y2_max = min(y2), max(y2)
    ax2.yaxis.set_major_locator(MaxNLocator(integer=True, nbins=10, min_n_ticks=2, prune='both', symmetric=False))
    ax2.set_ylim(y2_min, y2_max * 1.1)
    # 设置标题
    fig.suptitle("Energy drawing"
    # 添加图例
    lines, labels = ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax2.legend(lines + lines2, labels + labels2, loc='upper right')

    # 保存图表
    plt.savefig(path_to_save + "/示例图1.png")

    # 显示图表
    plt.show()

    # 关闭图表
    plt.close(fig)


if __name__ == "__main__":
    path_to_save = r"C:\Users\wayuper\Desktop"
    traverse_folder(r"C:\Users\wayuper\Documents\Materials Studio Projects\My Favorites\3C-SiC_Files\Documents") #遍历文件夹
    y3c()
    # 调用函数绘制表格
    tabledraw(data, path_to_save)
    # 调用函数绘制折线图
    plot_1(path_to_save, x1, y1, y2)

结果如下:

 具体代码如下:

import matplotlib.pyplot as plt
import os
import pandas as pd
from matplotlib.ticker import MaxNLocator
y1 = []
x1 = []
y2 = []
y11 = []
y3 = []
data = {}


def traverse_folder(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            # 打开文件
            ft = os.path.join(root, file)
            if ft[-6:] == "castep":
                with open(ft, 'r') as f:
                    text = f.readlines()  # 读取目标文件内容
                    for line in text:
                        if "MP grid size for SCF calculation is" in line:
                            tag = line.strip().split('is')[1].split()
                            tag = ''.join(tag)
                            if tag[:3] in ft:
                                x1.append(tag)
                                with open(ft, 'r') as l:
                                    text = l.readlines()  # 读取目标文件内容
                                    for i in text:
                                        if "Final Enthalpy" in i:
                                            data2 = i.strip().split('=')[1]
                                            y1.append(eval(data2[:-3])/18)
                                            y11.append(eval(data2[:-3]))
                                        if 'Total time' in i:
                                            data1 = i.strip().split('=')[1].strip()
                                            y2.append(eval(data1[:-1]))

    return x1, y1, y2


def y3c():
    for i in range(len(y1)):
        if i == 0:
            y3.append(i)
        else:
            y3.append(y1[i] - y1[i-1])
    data['k-points'] = x1
    data['System energy/eV'] = y11
    data['Average atomic energy/eV'] = y1
    data['Relative energy/eV'] = y3
    data['Calculation time/s'] = y2

    return y3, data


def tabledraw(data, path_to_save,dpi=300, figsize=(10, 6), fontsize=14):  
    # 创建一个简单的DataFrame(表格)  
    df = pd.DataFrame(data)  
  
    # 绘制表格  
    fig, ax = plt.subplots(figsize=figsize)  # 增大绘图窗口大小  
    ax.axis('off')  # 隐藏坐标轴  
  
    # 设置表格的位置和列标签  
    the_table = ax.table(cellText=df.values, colLabels=df.columns, loc='center', cellLoc='center')  
  
    # 调整单元格间距和字体大小  
    the_table.set_fontsize(fontsize)  
    the_table.scale(1, 2)  # 增大垂直方向上的缩放因子,使表格更高  
  
    # 隐藏坐标轴外的空白  
    plt.tight_layout()  
  
    # 保存图片  
    plt.savefig(path_to_save + "/表格2.png", dpi=dpi,bbox_inches='tight')
    
    # 显示图片
    plt.show()

def plot_1(path_to_save, x, y1, y2):
    fig, ax1 = plt.subplots(figsize=(20, 10), dpi=100)

    # 设置第一个y轴的属性
    ax1.set_xlabel("Encut/eV")
    ax1.set_ylabel("Average atomic energy/eV", color='b')
    ax1.tick_params('y', colors='b')
    ax1.grid(visible=True, which='major', linestyle='-', color='b', alpha=0.5)
    ax1.grid(visible=True, which='minor', linestyle='--', color='b', alpha=0.2)
    ax1.minorticks_on()
    ax1.plot(x, y1, '-o', color="b", label='Energy', linewidth=1)

    # 创建第二个y轴
    ax2 = ax1.twinx()

    # 设置第二个y轴的属性
    ax2.set_ylabel("Calculation time/s", color='r')
    ax2.tick_params('y', colors='r')
    ax2.grid(visible=True, which='major', linestyle='-', color='r', alpha=0.5)
    ax2.grid(visible=True, which='minor', linestyle='--', color='r', alpha=0.2)
    ax2.plot(x, y2, '-v', color="r", label='time', linewidth=1)
    y2_min, y2_max = min(y2), max(y2)
    ax2.yaxis.set_major_locator(MaxNLocator(integer=True, nbins=10, min_n_ticks=2, prune='both', symmetric=False))
    ax2.set_ylim(y2_min, y2_max * 1.1)
    # 设置标题
    fig.suptitle('k-points')

    # 添加图例
    lines, labels = ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax2.legend(lines + lines2, labels + labels2, loc='upper right')

    # 保存图表
    plt.savefig(path_to_save + "/示例图2.png")

    # 显示图表
    plt.show()

    # 关闭图表
    plt.close(fig)


if __name__ == "__main__":
    path_to_save = r"C:\Users\wayuper\Desktop"
    traverse_folder(r"C:\Users\wayuper\Documents\Materials Studio Projects\My Favorites\3C-SiC_Files\Documents") #遍历文件夹
    y3c()
    # 调用函数绘制折线图
    plot_1(path_to_save, x1, y1, y2)
    # 调用函数绘制表格
    tabledraw(data, path_to_save)

注:本人只是一个自学python的学渣,如有错误多多指正。😊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值