简体   繁体   English

如何使用 matplotlib 使用 .txt 文件中保存的数据绘制数据?

[英]How can I plot data using saved data from .txt file using matplotlib?

I'm trying to load a graph using user input data, and my program is supposed to save the values in a txt file with a format that looks like this:我正在尝试使用用户输入数据加载图形,并且我的程序应该将这些值保存在一个 txt 文件中,格式如下所示:

title标题

x-label x-标签

y-label y 标签

[a list of x-values] [x 值列表]

[a list of y-values] [y 值列表]

  • each on their own line.每个人都在自己的线上。

So what I have so far is:所以到目前为止我所拥有的是:

def lagre():
    filnavn = input("Hvilket filnavn vil du lagre grafen din med? ")
    fil = open(filnavn, 'w', encoding="UTF-8")
    fil.write(str(label) + "\n")
    fil.write(str(x_akse) + "\n")
    fil.write(str(y_akse) + "\n")
    fil.write(str(x_liste) + "\n")
    fil.write(str(y_liste) + "\n")
    fil.close()
    return

    
def load():
    filnavn_open = input("Hvilken graf vil du åpne? ")
    f = open(filnavn_open, "r")
    print(f.read())
    vise()
    
def vise():
    plt.plot(x_liste, y_liste)
    plt.title(label)
    plt.xlabel(x_akse)
    plt.ylabel(y_akse)
    plt.grid(True)
    plt.show()

But it doesn't work, could anybody help?但它不起作用,有人可以帮忙吗?

You read the whole file by using f.read() .您可以使用f.read()读取整个文件。 This means that calling f.readlines() afterwards returns an empty list.这意味着之后调用f.readlines() 会返回一个空列表。 You can save the file content in a variable and then use this in your plots or just use f.readlines() .您可以将文件内容保存在一个变量中,然后在您的绘图中使用它,或者只使用f.readlines()

Also you should close the file with f.close() .此外,您应该使用f.close()关闭文件。 Alternatively you can use the with ... as statement.或者,您可以使用with ... as语句。

So for example:例如:

def load():
    filnavn_open = input("Which graph do you want to open?")
    with open(filnavn_open, "r") as f:
        filecontent=f.read()
    print(filecontent)
    
    # plots with filecontent

There are two problems in your approach:你的方法有两个问题:

  1. the parameter size of the readline doesn't do what want to do, you can check out the documentation. readline的参数size没有做你想做的,你可以查看文档。

  2. The x and y values need to be converted from str to list , the ast package does that. x 和 y 值需要从str转换为listastast

Here is a working version:这是一个工作版本:

import ast
from matplotlib import pyplot as plt

def load():
    filnavn_open = input("Which graph do you want to open? ")
    lines = ['title', 'xlabel', 'ylabel', 'x-values', 'y-values']
    with open(filnavn_open, "r") as f:
        g = {val: f.readline().strip() for val in lines}
    plt.plot(ast.literal_eval(g['x-values']), ast.literal_eval(g['y-values']))
    plt.title(g['title'])
    plt.xlabel(g['xlabel'])
    plt.ylabel(g['ylabel'])
    plt.grid(True)
    plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM