如何从日志文件创建图表标题和标签?

时间:2017-02-21 06:04:07

标签: python-3.x csv matplotlib

在我的文件系统中,有一些标题和注释以及图形标签。图表标签由@启动     如何从日志文件中调用我的标题和x和y级别     由@提及?

@    title "RMSD"
@    xaxis  label "Time (ns)"
@    yaxis  label "RMSD (nm)"

脚本是:

import numpy as np
import matplotlib.pyplot as plt
import csv
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n","--filename", help="filename on")
args = parser.parse_args()
# example data
filename=(args.filename)

x, y = [],[]
with open(filename) as f:
    for line in f:
        cols = line.split()

        if line.split("#"):
           pass

        if line.split("@"):
           pass
        try:

           if len(cols) == 2:
                 x.append(float(cols[0]))
                 y.append(float(cols[1]))

         except ValueError:
           pass
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Temperature")  
ax1.set_xlabel("time in PS")  
ax1.set_ylabel("temp in K")
ax1.plot (x,y, c='r', label='the data')
leg = ax1.legend ()
plt.savefig('data.png', dpi=500)  

文件格式为:

# This file was created Wed May 25 12:05:43 2016
# Created by:
#                    :-) GROMACS - gmx rms, VERSION 5.1.2 (-:
# 
# Executable:   /usr/local/bin/gmx
# Data prefix:  /usr/local
# Command line:
#   gmx rms -s md_0_1.tpr -f md_0_1_noPBC.xtc -o rmsd.xvg -tu ns
# gmx rms is part of G R O M A C S:
#
# Great Red Oystrich Makes All Chemists Sane
#
@    title "RMSD"
@    xaxis  label "Time (ns)"
@    yaxis  label "RMSD (nm)"
@TYPE xy
@ subtitle "Backbone after lsq fit to Backbone"
    0.0000000    0.0005027
    0.0100000    0.0691386

1 个答案:

答案 0 :(得分:0)

你所拥有的方法已经很有希望了。 您基本上需要检查行中的第一个字符是否为@,如果是,请检查第二个单词。因此,您需要将标题,xlabel,ylabel设置为行中的联合剩余单词。

import numpy as np
import matplotlib.pyplot as plt
import csv
import argparse

filename = "SO_labelsfromcsv.txt"
x, y = [],[]
title = ""
xlabel = ""
ylabel = ""
with open(filename) as f:
    for line in f:
        cols = line.split()
        if cols[0][0] == "#":
            pass
        elif cols[0][0] == "@":
            if cols[1] == "title":
                title = " ".join(cols[2:]).replace('"', '')
            elif cols[1] == "xaxis":
                xlabel = " ".join(cols[3:]).replace('"', '')
            elif cols[1] == "yaxis":
                ylabel = " ".join(cols[3:]).replace('"', '')
        else:   
            try:
                if len(cols) == 2:
                     x.append(float(cols[0]))
                     y.append(float(cols[1]))
            except ValueError:
                pass
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x,y)
ax1.set_title(title)  
ax1.set_xlabel(xlabel)  
ax1.set_ylabel(ylabel)

plt.show()