Reputation: 29
This is my first time creating a graph on python. I have a text file holding data of "weekly gas averages". There are 52 of them (its a years worth of data). I understand how to read the data and make it into a list, I think, and I can do the basics of making a graph if I make the points myself. But I don't know how to connect the two, as in turn the data in the file into my X axis and then make my own Y axis (1-52). My code is a bunch of thoughts I've slowly put together. Any help or direction would be amazing.
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()
Upvotes: 0
Views: 1080
Reputation: 40667
Two errors I can spot while reading your code:
gasList
is already a list, so when you write x_coords = [gasList]
you're creating a list of list, which will not worky_coords=[1,53]
creates a list with only 2 values: 1 and 53. When you plot, you need to have as many y-values as there are x-values, so you should have 52 values in that list. You don't have to write them all by hand, you can use the function range(start, stop)
to do that for youThat being said, you will probably gain a lot by using the functions that have already been written for you. For instance, if you use the module numpy
(import numpy as np
), then you can use np.loadtxt()
to read the content of the file and create an array in one line. It's going to be much faster, and less error prone that trying to parse files by your self.
The final code:
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()
Upvotes: 1