You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将多个xvg格式文件的数据曲线绘制在同一张图表中

xvg多文件曲线对比绘图工具优化代码

优化说明

  • 新增全局列表存储所有选中的xvg文件,支持添加任意数量的待处理文件
  • 补全原代码遗漏的random库依赖,同时调整随机颜色生成规则适配matplotlib的颜色值规范
  • 文件选择时自动过滤仅显示xvg格式文件,降低误选概率
  • 所有文件的曲线将绘制在同一张画布中,图例默认使用对应文件名,不同曲线自动分配不同颜色
  • 增加空选择校验,避免未选文件时点击绘图触发报错

完整可运行代码

from tkinter import *
import matplotlib.pyplot as plt
import numpy as np
from tkinter import filedialog
import random
import os

plt.rcParams.update({'font.size':15})
root = Tk()
root.title("Graph plotter")
root.geometry("900x800")
# 全局存储所有选中的xvg文件路径
file_list = []

def processxvg(filename):
    x, y = [], []
    with open(filename) as f:
        for line in f:
            if line[0] != "#" and line[0] != "@":
                cols = line.split()
                if len(cols) == 2:
                    x.append(float(cols[0]))
                    y.append(float(cols[1]))
    return x,y

def random_color():
    levels = range(32,256,32)
    # 转换为matplotlib支持的0-1范围RGB值
    return tuple(random.choice(levels)/255 for _ in range(3))

def browsefunc():
    global file_list
    # 限制仅选择xvg格式文件
    filename = filedialog.askopenfilename(filetypes=[("XVG格式文件", "*.xvg")])
    if filename:
        file_list.append(filename)
        # 更新路径标签显示信息
        show_files = "\n".join([os.path.basename(f) for f in file_list[-3:]])
        pathlabel.config(text=f"已选文件总数:{len(file_list)}个\n最近选择的文件:\n{show_files}")

def addbox():
    browsebutton = Button(root, text="Browse", command=browsefunc)
    browsebutton.pack()

my_label = Label(root, text= "Browse the xvg file in the dir", font =("Ariel", "20") )
my_label.pack()

pathlabel = Label(root)
pathlabel.pack()

def clicked1():
    # 校验是否已选择文件
    if not file_list:
        pathlabel.config(text="错误:请先选择至少一个xvg文件后再绘图")
        return
    f = plt.figure()
    f.set_figwidth(20)
    f.set_figheight(10)
    # 遍历所有文件逐一绘图
    for file in file_list:
        x, y = processxvg(file)
        line_color = random_color()
        plt.plot(x, y, color=line_color, label=os.path.basename(file))
    plt.xlabel("Time (ns)", fontsize="35", labelpad=25)
    plt.ylabel("RMSD (nm)", fontsize="35", labelpad=25)
    plt.legend(fontsize=15)
    plt.show()

add_files_button = Button(root, text ="Add files", command = addbox)
add_files_button.pack()

plotbutton = Button(root, text ="Plot", command = clicked1 )
plotbutton.pack(pady = 10)

root.mainloop()

内容的提问来源于stack exchange,提问作者AKA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 11:45:03