Python Forum
Graphic line plot with matplotlib, text file in pytho - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Graphic line plot with matplotlib, text file in pytho (/thread-37945.html)



Graphic line plot with matplotlib, text file in pytho - khadija - Aug-12-2022

hello, I want to display a graph using data from a text file with matplotlib and I am having some problems. Data is sent and received via sockets and stored in a text file.

here is my code:
import matplotlib.pyplot as plt



X = []
Y = []




fichier = open('orde.txt', 'r')


for row in fichier:
    row=row.split(' ')
    if len(row)>0:
     X.append(row[0])
     Y.append(row[-1])



plt.xlabel('Time' , fontsize = 12)
plt.ylabel('Amplitude', fontsize = 12)
plt.plot(X, Y ,color = 'red', label = 'signal')

plt.title('Courbe', fontsize = 20)
plt.show()



RE: Graphic line plot with matplotlib, text file in pytho - deanhystad - Aug-12-2022

Looks like your data is in a text file, but you are treating it like the file contains floats. You need to read the value strings from the file and convert them to float. You could do this yourself, but I suggest using the csv library or pandas.

csv_reader will remove newlines and split entries by delimiter automatically. It is a cleaner way of doing what you are currently doing, but it does not convert the values to float.
https://docs.python.org/3/library/csv.html

pandas read_csv does all the things csv_reader does and it converts the values from strings to floats.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html


RE: Graphic line plot with matplotlib, text file in pytho - khadija - Aug-15-2022

(Aug-12-2022, 06:18 PM)deanhystad Wrote: Looks like your data is in a text file, but you are treating it like the file contains floats. You need to read the value strings from the file and convert them to float. You could do this yourself, but I suggest using the csv library or pandas.

csv_reader will remove newlines and split entries by delimiter automatically. It is a cleaner way of doing what you are currently doing, but it does not convert the values to float.
https://docs.python.org/3/library/csv.html

pandas read_csv does all the things csv_reader does and it converts the values from strings to floats.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html



Ah Okay, i will try the link. Thanks