How To Plot ASCII File In Python

In this tutorial, we will learn how to plot data from an ASCII file in Python using the popular plotting library, Matplotlib. Ascii files are plain text files containing data, often represented by numbers or letters. They are widely used in scientific research and engineering applications for storing and exchanging data.

To demonstrate how to plot the data from an ASCII file, we will create a simple file containing the values of the sine function and then plot the data using Matplotlib. Let’s get started!

Step 1: Install and Import the Required Libraries

Before we start, we need to install and import the required libraries. In this tutorial, we will use the NumPy library for numerical operations and Matplotlib for plotting the data. If you do not have these libraries installed, you can install them using the following commands:

Now, let’s import the required libraries in your Python script.

Step 2: Create an ASCII File

For this tutorial, we will create a simple ASCII file containing two columns: the first column will contain the x-values, and the second column will contain the corresponding y-values (sine of x-values).

We will use NumPy’s savetxt function to generate and save the data as an ASCII file.

This will create a file named data.txt in your working directory.

Here's the content of data.txt (first 5 rows):

0.00000000e+00  0.00000000e+00
6.34617594e-02  6.34239197e-02
1.26943547e-01  1.26592454e-01
1.90415910e-01  1.89251244e-01
2.53910261e-01  2.51147987e-01
...

Step 3: Read and Plot the Data from the ASCII File

Now that we have our ASCII file ready, we can read the data from this file using NumPy’s loadtxt function and then plot the data using Matplotlib.

This will display a plot of the sine function as read from the ASCII file.

Full Code

Output

Conclusion

In this tutorial, we learned how to plot data from an ASCII file in Python using NumPy and Matplotlib. We created a simple ASCII file containing values of the sine function, read the data from the file, and plotted it using Matplotlib. By following these steps, you can plot any data from an ASCII file in Python for your specific application.