Advertisement
Python253

plot_test_arrays

May 24th, 2024
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.63 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: plot_test_arrays.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    This script reads a file containing arrays and plots each array with smooth splines and data point markers.
  10.    It opens each plot individually and allows the user to interact with it, save the image, and then close the plot window.
  11.  
  12. Requirements:
  13.    - Python 3.x
  14.    - matplotlib
  15.    - numpy
  16.    - scipy
  17.  
  18. Functions:
  19.    - read_arrays_from_file(filename):
  20.        Reads arrays from a file.
  21.    - plot_array_with_spline(data_array):
  22.        Plots a single array with smooth splines and data point markers.
  23.    - select_file():
  24.        Prompts the user to select a file from the current working directory.
  25.  
  26. Usage:
  27.    - Run the script and select the file containing the arrays to plot.
  28. """
  29.  
  30. import matplotlib.pyplot as plt
  31. import numpy as np
  32. from scipy.interpolate import make_interp_spline
  33. import re
  34. import os
  35. import sys
  36. from tkinter import Tk
  37. from tkinter.filedialog import askopenfilename
  38.  
  39. def read_arrays_from_file(filename):
  40.     """
  41.    Read arrays from a file.
  42.  
  43.    Parameters:
  44.    filename (str): The name of the file to read the arrays from.
  45.  
  46.    Returns:
  47.    list: A list of arrays read from the file.
  48.    """
  49.     arrays = []
  50.     with open(filename, 'r') as file:
  51.         for line in file:
  52.             match = re.search(r'\[(.*)\]', line)
  53.             if match:
  54.                 array_str = match.group(1)
  55.                 array = [float(num) for num in array_str.split(', ')]
  56.                 arrays.append(array)
  57.     return arrays
  58.  
  59. def plot_array_with_spline(data_array):
  60.     """
  61.    Plot a single array with smooth splines and data point markers.
  62.  
  63.    Parameters:
  64.    data_array (list): The array to plot.
  65.    """
  66.     x = np.arange(len(data_array))
  67.     y = data_array
  68.     spline = make_interp_spline(x, y)
  69.     x_smooth = np.linspace(x.min(), x.max(), 300)
  70.     y_smooth = spline(x_smooth)
  71.  
  72.     plt.plot(x_smooth, y_smooth, color='red', linewidth=2, label='Smooth Spline')
  73.     plt.scatter(x, y, color='blue', marker='o', label='Array Points')
  74.     plt.fill_between(x_smooth, y_smooth, color='pink', alpha=0.3)  # Fill under the spline with color
  75.     for j, txt in enumerate(data_array):
  76.         plt.annotate('{:.2f}'.format(txt), (x[j], y[j]), textcoords="offset points", xytext=(0,10), ha='center')
  77.     plt.xlabel('Index')
  78.     plt.ylabel('Value')
  79.     plt.title('Array Plot with Smooth Spline')
  80.     plt.legend()
  81.     plt.grid(True)
  82.  
  83. def select_file():
  84.     """
  85.    Prompts the user to select a file from the current working directory.
  86.  
  87.    Returns:
  88.    str: The selected file path.
  89.    """
  90.     root = Tk()
  91.     root.withdraw()  # Hide the main window
  92.     filepath = askopenfilename(initialdir=os.getcwd(), title="Select a file", filetypes=[("Text files", "*.txt")])
  93.     root.destroy()  # Destroy the Tkinter window
  94.     return filepath
  95.  
  96. if __name__ == "__main__":
  97.     # Prompt the user to select a file containing the arrays
  98.     print("\nSelect the file containing the arrays to plot.\n")
  99.     file_path = select_file()
  100.     # Catch if the user cancels selection & exit gracefully
  101.     if not file_path:
  102.         print("\tNo file selected!\n\nExiting Program...   GoodBye!\n")
  103.         sys.exit(1)
  104.  
  105.     # Read arrays from the selected file
  106.     arrays = read_arrays_from_file(file_path)
  107.  
  108.     # Plot each array
  109.     for i, array in enumerate(arrays, start=1):
  110.         print("Plotting Array {}...".format(i))
  111.         plot_array_with_spline(array)
  112.         plt.show()
  113.    
  114.     # Exit program
  115.     print("\nAll plots are complete.\n\nExiting program...   GoodBye!")
  116.     sys.exit(0)
  117.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement