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

问题描述 投票:0回答:1

这是我第一次在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()
python matplotlib linegraph
1个回答
1
投票

阅读代码时我会发现两个错误:

  • 对象gasList已经是一个列表,因此当您编写x_coords = [gasList]时,您正在创建一个列表列表,该列表将不起作用
  • y_coords=[1,53]行创建的列表仅包含2个值:1和53。绘制时,您需要的y值与x值一样多,因此该列表中应有52个值。您不必全部手工编写,可以使用函数range(start, stop)为您完成此操作

话虽如此,使用已经为您编写的功能,您可能会收获很多。例如,如果使用模块range(start, stop)numpy),则可以使用import numpy as np读取文件的内容并在一行中创建一个数组。它将比尝试自行分析文件的速度更快,并且出错的可能性也更低。

最终代码:

np.loadtxt()

np.loadtxt()

© www.soinside.com 2019 - 2024. All rights reserved.