Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: array_plotter.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script reads multiple arrays from a file and plots each array as a smooth spline on a single graph.
- - It displays a legend showing the average values of each array.
- - Additionally, the script prints the indices, values, and averages of each array to the console.
- Requirements:
- - Python 3.x
- - matplotlib
- - numpy
- - scipy
- - tkinter
- Functions:
- - read_arrays_from_file(file_path):
- Reads arrays from the specified file.
- - select_file():
- Prompts the user to select a file using a file dialog.
- - plot_arrays(arrays):
- Plots the given arrays with smooth splines and displays the average values in the legend.
- - main():
- The main function that coordinates reading the file, printing array details, plotting the arrays, and handling any errors.
- Usage:
- - Run the script in a Python environment with the required libraries installed.
- - A file dialog will prompt you to select a file containing arrays.
- - The script will print the array indices, values, and averages to the console.
- - A plot window will display the arrays with smooth splines and a legend showing their average values.
- - Closing the plot window will terminate the script with a goodbye message.
- Additional Notes:
- - Ensure the input file is properly formatted, with each array on a new line and values separated by commas.
- - The script uses Tkinter for the file dialog, which may require a GUI environment to run properly.
- """
- import os
- import tkinter as tk
- from tkinter import filedialog
- import numpy as np
- import matplotlib.pyplot as plt
- from scipy.interpolate import make_interp_spline
- def read_arrays_from_file(file_path):
- """
- Reads arrays of floating-point numbers from a specified file.
- Args:
- file_path (str): The path to the file containing arrays.
- Returns:
- list of list of float: A list where each element is a list of floating-point numbers
- representing an array from the file.
- """
- with open(file_path, 'r') as file:
- lines = file.readlines()
- arrays = []
- for line in lines:
- array = [float(num.strip('[],\n')) for num in line.split()]
- arrays.append(array)
- return arrays
- def select_file():
- """
- Opens a file dialog for the user to select a file containing arrays.
- Returns:
- str: The file path of the selected file, or an empty string if no file was selected.
- """
- root = tk.Tk()
- root.withdraw() # Hide the main window
- file_path = filedialog.askopenfilename(title="Select file with arrays", filetypes=[("Text files", "*.txt")])
- return file_path
- def plot_arrays(arrays):
- """
- Plots the given arrays with smooth splines and displays the average values in the legend.
- Args:
- arrays (list of list of float): A list where each element is a list of floating-point numbers
- representing an array to plot.
- """
- colors = plt.cm.tab10(np.linspace(0, 1, len(arrays)))
- for i, array in enumerate(arrays):
- x = np.arange(len(array))
- y = np.array(array)
- x_smooth = np.linspace(x.min(), x.max(), 300)
- spl = make_interp_spline(x, y, k=3)
- y_smooth = spl(x_smooth)
- avg_value = np.mean(array)
- label = f'A{i+1:02d} ( Avg: {avg_value:.2f})' if i < 9 else f'A{i+1:02d} (Avg: {avg_value:.2f})'
- plt.plot(x_smooth, y_smooth, color=colors[i], label=label)
- plt.scatter(x, y, color=colors[i], marker='o')
- plt.xlabel('Index')
- plt.ylabel('Value')
- plt.title('Arrays Plot')
- plt.grid(True)
- plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
- plt.show()
- def main():
- """
- The main function that coordinates reading the file, printing array details, plotting the arrays,
- and handling any errors.
- """
- print("-" * 25)
- file_path = select_file()
- if not file_path:
- print("\nNo file selected!\n\nExiting Program... GoodBye!\n")
- return
- try:
- arrays = read_arrays_from_file(file_path)
- overall_averages = []
- for i, array in enumerate(arrays):
- print(f"Array {i + 1} Index:")
- for idx, val in enumerate(array, start=1):
- print(f" {idx}: {val}")
- average = np.mean(array)
- overall_averages.append(average)
- print(f"Array {i + 1} Average: {average:.2f}\n")
- print("-" * 25)
- print("All Arrays Averages:\n")
- for i, average in enumerate(overall_averages, start=1):
- print(f" Array {i} Average: {average:.2f}")
- plot_arrays(arrays)
- except Exception as e:
- print(f"\nAn error occurred: {e}")
- exit(1)
- print("\nPlot window closed. Goodbye!")
- exit(0)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement