close

How can you plot data from a .txt file using matplotlib?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can you plot data from a .txt file using matplotlib in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can you plot data from a .txt file using matplotlib?

  1. How can you plot data from a .txt file using matplotlib?

    Please keep in mind that you are saving str into a list. If you want to plot x and y using matplotlib, I suggest to change the format from 'str' to 'int' or 'float':

  2. you plot data from a .txt file using matplotlib

    Please keep in mind that you are saving str into a list. If you want to plot x and y using matplotlib, I suggest to change the format from 'str' to 'int' or 'float':

Method 1

You’re just reading in the data wrong. Here’s a cleaner way:

with open('Alpha_Particle.txt') as f:
    lines = f.readlines()
    x = [line.split()[0] for line in lines]
    y = [line.split()[1] for line in lines]

x
['6876.593750', '6876.302246', '6876.003418']

y
['1', '1', '0']

Method 2

Please keep in mind that you are saving str into a list. If you want to plot x and y using matplotlib, I suggest to change the format from ‘str’ to ‘int’ or ‘float’:

import matplotlib.pyplot as plt
with open('filename.txt', 'r') as f:
    lines = f.readlines()
    x = [float(line.split()[0]) for line in lines]
    y = [float(line.split()[1]) for line in lines]
plt.plot(x ,y)
plt.show()

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read