Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: plot_test_arrays.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script reads a file containing arrays and plots each array with smooth splines and data point markers.
- It opens each plot individually and allows the user to interact with it, save the image, and then close the plot window.
- Requirements:
- - Python 3.x
- - matplotlib
- - numpy
- - scipy
- Functions:
- - read_arrays_from_file(filename):
- Reads arrays from a file.
- - plot_array_with_spline(data_array):
- Plots a single array with smooth splines and data point markers.
- - select_file():
- Prompts the user to select a file from the current working directory.
- Usage:
- - Run the script and select the file containing the arrays to plot.
- """
- import matplotlib.pyplot as plt
- import numpy as np
- from scipy.interpolate import make_interp_spline
- import re
- import os
- import sys
- from tkinter import Tk
- from tkinter.filedialog import askopenfilename
- def read_arrays_from_file(filename):
- """
- Read arrays from a file.
- Parameters:
- filename (str): The name of the file to read the arrays from.
- Returns:
- list: A list of arrays read from the file.
- """
- arrays = []
- with open(filename, 'r') as file:
- for line in file:
- match = re.search(r'\[(.*)\]', line)
- if match:
- array_str = match.group(1)
- array = [float(num) for num in array_str.split(', ')]
- arrays.append(array)
- return arrays
- def plot_array_with_spline(data_array):
- """
- Plot a single array with smooth splines and data point markers.
- Parameters:
- data_array (list): The array to plot.
- """
- x = np.arange(len(data_array))
- y = data_array
- spline = make_interp_spline(x, y)
- x_smooth = np.linspace(x.min(), x.max(), 300)
- y_smooth = spline(x_smooth)
- plt.plot(x_smooth, y_smooth, color='red', linewidth=2, label='Smooth Spline')
- plt.scatter(x, y, color='blue', marker='o', label='Array Points')
- plt.fill_between(x_smooth, y_smooth, color='pink', alpha=0.3) # Fill under the spline with color
- for j, txt in enumerate(data_array):
- plt.annotate('{:.2f}'.format(txt), (x[j], y[j]), textcoords="offset points", xytext=(0,10), ha='center')
- plt.xlabel('Index')
- plt.ylabel('Value')
- plt.title('Array Plot with Smooth Spline')
- plt.legend()
- plt.grid(True)
- def select_file():
- """
- Prompts the user to select a file from the current working directory.
- Returns:
- str: The selected file path.
- """
- root = Tk()
- root.withdraw() # Hide the main window
- filepath = askopenfilename(initialdir=os.getcwd(), title="Select a file", filetypes=[("Text files", "*.txt")])
- root.destroy() # Destroy the Tkinter window
- return filepath
- if __name__ == "__main__":
- # Prompt the user to select a file containing the arrays
- print("\nSelect the file containing the arrays to plot.\n")
- file_path = select_file()
- # Catch if the user cancels selection & exit gracefully
- if not file_path:
- print("\tNo file selected!\n\nExiting Program... GoodBye!\n")
- sys.exit(1)
- # Read arrays from the selected file
- arrays = read_arrays_from_file(file_path)
- # Plot each array
- for i, array in enumerate(arrays, start=1):
- print("Plotting Array {}...".format(i))
- plot_array_with_spline(array)
- plt.show()
- # Exit program
- print("\nAll plots are complete.\n\nExiting program... GoodBye!")
- sys.exit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement