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

问题描述

我正在尝试使用用户输入数据加载图形,并且我的程序应该将值保存在txt文件中,格式如下:

标题

x-label

y-label

[x值列表]

[y值列表]

  • 每人一行。

所以我到目前为止是:

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()

但是它不起作用,有人可以帮忙吗?

解决方法

您使用 f.read()读取了整个文件。这意味着之后调用 f.readlines()会返回一个空列表。您可以将文件内容保存在变量中,然后在绘图中使用它,也可以只使用 f.readlines()

此外,您还应该使用 f.close()关闭文件。另外,您也可以使用 with ... as 语句。

例如:

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
,

您的方法有两个问题:

  1. size的参数readline并没有执行您想做的事情,您可以查看文档。

  2. 需要将x和y值从str转换为listast包可以做到这一点。

这是一个有效的版本:

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()