save data to file in plot in python

To save data to a file and plot it using Python, you can follow these steps:

  1. Import the necessary libraries. For file handling, you can use the csv module, and for data visualization, you can use matplotlib.
main.py
import csv
import matplotlib.pyplot as plt
43 chars
3 lines
  1. Create a list of data that you want to save and plot. For example, let's say you have two lists x and y representing the x-coordinates and y-coordinates of the data points:
main.py
x = [1, 2, 3, 4, 5]
y = [10, 12, 8, 15, 11]
44 chars
3 lines
  1. Open a file to write the data into using the csv.writer function. Specify the file name, mode as 'w' (write), and delimiter (comma in this case) to separate the values:
main.py
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter=',')
93 chars
3 lines
  1. Write the data into the file using the writer.writerow() method. Pass the data as a list of values to be written in each row:
main.py
    for i in range(len(x)):
        writer.writerow([x[i], y[i]])
66 chars
3 lines
  1. Close the file after writing the data:
main.py
file.close()
13 chars
2 lines
  1. Now, you can use matplotlib to plot the data from the file. Read the data from the file using the csv.reader function. Specify the file name and delimiter similar to the file writing step:
main.py
with open('data.csv', 'r') as file:
    reader = csv.reader(file, delimiter=',')
81 chars
3 lines
  1. Extract the x and y values from the file by iterating over the rows using a loop and appending them to new lists:
main.py
    x = []
    y = []
    for row in reader:
        x.append(float(row[0]))
        y.append(float(row[1]))
109 chars
6 lines
  1. Finally, plot the data using matplotlib:
main.py
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Data Plot')
plt.show()
81 chars
6 lines

This will save the data to a file and plot it using Python. Make sure to modify the file name and path according to your requirements.

gistlibby LogSnag