【问题标题】:Creating a function to read two text files and plot a graph from it创建一个函数来读取两个文本文件并从中绘制图表
【发布时间】:2020-10-17 13:29:51
【问题描述】:

我是新来的,所以请多多包涵。 我正在尝试从不同的 x,y 数组文本文件创建多个图形。这基本上是我用来创建图表的代码的主干。

import numpy as np
import matplotlib.pyplot as plt

filename = the_data_path

np.savetxt(filename, np.transpose([x,y]), delimiter=',', header= "x_values, y_values")

这些是我用来从文本文件中的数组创建图表的线,因此有 2 个数据集正在比较。

line1 = np.genfromtxt("file1.txt", names = True, delimiter = ",")
plt.plot(line1["x_values"], line1["y_values"])
line2 = np.genfromtxt("file2.txt", names = True, delimiter = ",")
plt.plot(line2["x_values"], line2["y_values"])
plt.show()

现在我正在尝试创建一个函数,该函数将包含来自第二个单元格的代码,以便能够更轻松地为来自不同数据文件的多个其他图形调用它。任何关于前进方向的建议都会很棒。我尝试了一些以def my_plot(): 开头的其他方法,但没有返回图表。

抱歉,这太长了,非常感谢您提前抽出时间!!

【问题讨论】:

    标签: python function numpy matplotlib graph


    【解决方案1】:

    如果您尝试遍历存储 numpy 数组的所有文件,您可以像这样定义您的函数:

    def my_plot():
      # n is the number of files you have containing numpy arrays
      for i in range(1,n):
        fname = f"file{i}.txt"
        line = np.genfromtxt(fname, names = True, delimiter = ",")
        plt.plot(line["x_values"], line["y_values"])
      
      #now plotting the graph
      plt.show()
    

    【讨论】:

    • 如果我的回答对你有用,你能接受吗?谢谢!
    • 是的,很抱歉,我不知道它是如何工作的,这是我自己的第一个问题。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2021-07-15
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多