从文本文件中绘制一行数据

2024-10-01 02:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次在python上创建图形。我有一个文本文件,保存着“每周平均煤气量”的数据。其中有52个(相当于一年的数据)。我知道如何读取数据并将其列成一个列表,我认为,如果我自己给出这些点,我就可以完成绘制图表的基础工作。但我不知道如何将两者连接起来,因为文件中的数据依次转换为我的X轴,然后生成我自己的Y轴(1-52)。我的代码是我慢慢拼凑起来的一堆想法。任何帮助或指导都会令人惊讶

    import matplotlib.pyplot as plt

    def main():
        print("Welcome to my program. This program will read data 
    off a file"\
  +" called 1994_Weekly_Gas_Averages.txt. It will plot the"\
  +" data on a line graph.")
        print()

        gasFile = open("1994_Weekly_Gas_Averages.txt", 'r')

        gasList= []

        gasAveragesPerWeek = gasFile.readline()

        while gasAveragesPerWeek != "":
            gasAveragePerWeek = float(gasAveragesPerWeek)
            gasList.append(gasAveragesPerWeek)
            gasAveragesPerWeek = gasFile.readline()

        index = 0
        while index<len(gasList):
            gasList[index] = gasList[index].rstrip('\n')
            index += 1

        print(gasList)

        #create x and y coordinates with data
        x_coords = [gasList]
        y_coords = [1,53]

        #build line graph
        plt.plot(x_coords, y_coords)

        #add title
        plt.title('1994 Weekly Gas Averages')

        #add labels
        plt.xlabel('Gas Averages')
        plt.ylabel('Week')

        #display graph
        plt.show()

    main()

Tags: 数据dataindexmainpltcoordsprogramgraph
1条回答
网友
1楼 · 发布于 2024-10-01 02:39:02

在阅读代码时,我可以发现两个错误:

  • 对象gasList已经是一个列表,因此当您编写x_coords = [gasList]时,您正在创建一个列表列表,这将不起作用
  • y_coords=[1,53]创建了一个只有2个值的列表:1和53。打印时,y值的数量必须与x值的数量相同,因此该列表中应该有52个值。您不必全部手工编写,您可以使用函数^{}来完成

也就是说,通过使用已经为您编写的函数,您可能会获得很多好处。例如,如果使用模块numpyimport numpy as np),则可以使用^{}读取文件内容并在一行中创建数组。与您自己解析文件相比,它将更快,更不容易出错

最终代码:

import matplotlib.pyplot as plt
import numpy as np


def main():
    print(
        "Welcome to my program. This program will read data off a file called 1994_Weekly_Gas_Averages.txt. It will "
        "plot the data on a line graph.")
    print()

    gasFile = "1994_Weekly_Gas_Averages.txt"

    gasList = np.loadtxt(gasFile)
    y_coords = range(1, len(gasList) + 1)  # better not hardcode the length of y_coords, 
                                           # in case there fewer values that expected

    # build line graph
    plt.plot(gasList, y_coords)

    # add title
    plt.title('1994 Weekly Gas Averages')

    # add labels
    plt.xlabel('Gas Averages')
    plt.ylabel('Week')

    # display graph
    plt.show()


if __name__ == "__main__":
    main()

enter image description here

相关问题 更多 >