【问题标题】:plot data from more than one text file using python使用python从多个文本文件中绘制数据
【发布时间】:2020-09-17 22:17:34
【问题描述】:

我有两个文件。 Xdata.txtYdata.txtXdata 的每一行都应与Ydata 的每一行进行对比。 关键是每行中的列数不同。 例如:

Xdata.txt

row1: 1 2 3 4 5 6
row2: 1 2 3 4

Ydata.txt

row1: 1 2 3 4 5 6
row2: 1 2 3 4

我想画

Xdata[row1], Ydata[row1]

Xdata=[row2], Ydata[row2]

在一个数字中。请帮我解决这种情况。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以通过将每个文件加载到列表中来开始该过程。

    with open("Xdata.txt", "r") as xf:
        x_list = xf.readlines()
    
    with open("Ydata.txt", "r") as yf:
        y_list = yf.readlines()
    
    

    然后,您使用 python 的zip 函数来获取每对线并绘制它们。这会将 Xdata.txt 中的第 1 行与 Ydata.txt 中的第 1 行配对,依此类推:

    for (x_line, y_line) in zip(x_list, y_list):
        # Split out the data from the line, which is stored as a string
        x_data = x_line.split(' ')
        y_data = y_line.split(' ')
    
        # Insert data conversion from string to numbers if needed
    
        # Modify plotting code as needed
        plot(x_data, y_data)
    

    【讨论】:

    • 嗨;我得到:for (x_line, y_line) in zip(x_list, y_list): TypeError: 'builtin_function_or_method' object is not iterable
    • @mohammad24 我的错,应该是readlines(),而不是readlines。尝试将列表打印出来,看看是否符合您的预期
    【解决方案2】:

    试试这个(@jrmylow 答案的实现):

    输入

    Xdata.txt 
    
    1 4 3 6 5 6
    1 2 3 7
    
    Ydata.txt 
    
    1 2 3 4 5 6
    1 2 3 4
    
    import matplotlib.pyplot as plt
      
    with open("Xdata.txt", "r") as xf:
        x_list = xf.readlines()
    
    with open("Ydata.txt", "r") as yf:
        y_list = yf.readlines()
    
    for (x_line, y_line) in zip(x_list, y_list):
        x_data = x_line.split(' ')
        y_data = y_line.split(' ')
        plt.plot(x_data, y_data)
    
    plt.legend(['first','second'])
    plt.show()
    

    【讨论】:

    • 如果对您有用,请点赞并接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2023-03-29
    • 2017-12-12
    • 1970-01-01
    • 2020-06-21
    • 2018-11-28
    相关资源
    最近更新 更多