Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Plot data from a .txt file using matplotlib
To plot data from a .txt file using matplotlib, we can read the file line by line, extract the data, and create visualizations. This is useful for analyzing data stored in simple text formats.
Steps to Plot Data from Text File
- Set the figure size and adjust the padding between and around the subplots
- Initialize empty lists for data storage
- Open the .txt file in read mode and parse each line
- Extract values and append to respective lists
- Create the plot using matplotlib
- Display the figure using show() method
Sample Data File
First, let's see the structure of our sample data file "test_data.txt" ?
Javed 12 Raju 14 Rishi 15 Kiran 10 Satish 17 Arun 23
Creating a Bar Plot from Text File
Here's how to read the text file and create a bar plot ?
import matplotlib.pyplot as plt
# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Initialize empty lists for data
bar_names = []
bar_heights = []
# Sample data (simulating file content)
data_lines = [
"Javed 12",
"Raju 14",
"Rishi 15",
"Kiran 10",
"Satish 17",
"Arun 23"
]
# Process each line of data
for line in data_lines:
bar_name, bar_height = line.split()
bar_names.append(bar_name)
bar_heights.append(int(bar_height))
# Create bar plot
plt.bar(bar_names, bar_heights)
plt.title('Data from Text File')
plt.xlabel('Names')
plt.ylabel('Values')
plt.show()
Reading from Actual File
When reading from an actual text file, use this approach ?
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
bar_names = []
bar_heights = []
# Read from actual file
with open("test_data.txt", "r") as file:
for line in file:
bar_name, bar_height = line.strip().split()
bar_names.append(bar_name)
bar_heights.append(int(bar_height))
plt.bar(bar_names, bar_heights)
plt.title('Data from Text File')
plt.xlabel('Names')
plt.ylabel('Values')
plt.show()
Advanced Example with Multiple Columns
For text files with multiple numeric columns, you can create more complex plots ?
import matplotlib.pyplot as plt
import numpy as np
# Sample data with multiple columns
data_lines = [
"Jan 20 25 30",
"Feb 22 28 32",
"Mar 25 30 35",
"Apr 28 32 38"
]
months = []
temp_min = []
temp_avg = []
temp_max = []
for line in data_lines:
parts = line.split()
months.append(parts[0])
temp_min.append(int(parts[1]))
temp_avg.append(int(parts[2]))
temp_max.append(int(parts[3]))
# Create multiple line plot
plt.figure(figsize=(10, 6))
plt.plot(months, temp_min, label='Min Temp', marker='o')
plt.plot(months, temp_avg, label='Avg Temp', marker='s')
plt.plot(months, temp_max, label='Max Temp', marker='^')
plt.title('Temperature Data from Text File')
plt.xlabel('Months')
plt.ylabel('Temperature (°C)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Error Handling
Always include error handling when reading files ?
import matplotlib.pyplot as plt
try:
bar_names = []
bar_heights = []
with open("test_data.txt", "r") as file:
for line in file:
if line.strip(): # Skip empty lines
parts = line.strip().split()
if len(parts) >= 2:
bar_names.append(parts[0])
bar_heights.append(float(parts[1]))
plt.bar(bar_names, bar_heights)
plt.title('Data from Text File')
plt.show()
except FileNotFoundError:
print("File not found. Please check the file path.")
except ValueError:
print("Error parsing data. Check file format.")
Conclusion
Reading data from text files with matplotlib is straightforward using file reading operations and split() method. Always include error handling and use with statement for proper file handling. This approach works well for simple datasets stored in plain text format.
