How to plot a graph in python using a file containing numpy arrays?

Asked

Viewed 207 times

3

Good afternoon! I am creating a python program that plots the graph of the quadratic function (y=x**2), however, you need to put the data of x and y in a file and plot the graph by extracting the data from that file, but I am not able to do that. I will be grateful for the help, because I am a beginner in language and I do not know many functionality. Follow what I can do until then:

import numpy as np
import matplotlib.pyplot as plt 

start = float(input('valor inicial: '))
stop = float(input('valor final: '))

x = np.arange(start, stop+1) 

y = x**2

arq = open('dados.dat','w')
arq.write(str(x))
arq.write(str(y))
arq.close()

plt.plot()
plt.show()
  • Does the array data need to be written in text format? If it is possible to save in binary format, you can save directly with the np.save: https://numpy.org/doc/stable/reference/generated/numpy.save.html#numpy.save

  • I believe so. If possible, in this case, how would I plot the graph?

  • Do you want to read a file and then plot x and y? If yes, send an example of that file

  • If your idea isn’t to save to the file, just replace the Plot plt.plot(x, y)

  • I want to read the file and then plot the graph the file as follows: [-10. -9. -8. -7. -6. -5. -4. -3. -2. -1. 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. ][100. 81. 64. 49. 36. 16. 9. 4. 1. 0. 1. 4. 9. 16. 25. 36. 49. 64. 81. 100. ] (I used an example ranging from -10 to 10, from [ to where you have "][" eh x, dps disso eh o y )

1 answer

1

To save data to file:

import numpy as np

start = float(input('valor inicial: '))
stop = float(input('valor final: '))

x = np.arange(start, stop+1) 

y = x**2

np.savetxt('dados.dat', [x, y], delimiter=",")

To read the file data and plot:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt('dados.dat', delimiter = ",")

plt.plot(x, y)
plt.show()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.