Okay, here's a Python script using matplotlib and numpy to load your sliding_scores-10-pos.npy array and plot it as a histogram.
First, make sure you have the necessary libraries installed:
If you don't have them, install them using pip:
pip install numpy matplotlib
Python Script:
import numpy as np
import matplotlib.pyplot as plt
import os
# --- Configuration ---
FILE_NAME = 'sliding_scores-10-pos.npy'
NUMBER_OF_BINS = 30 # Adjust as needed, or use 'auto' for automatic binning
# Examples for NUMBER_OF_BINS: 20, 50, 'auto', 'fd' (Freedman-Diaconis rule)
def plot_histogram_from_npy(file_path, num_bins):
"""
Loads data from a .npy file and plots its histogram.
Args:
file_path (str): The path to the .npy file.
num_bins (int or str): The number of bins for the histogram (e.g., 30, 'auto').
"""
# 1. Check if the file exists
if not os.path.exists(file_path):
print(f"Error: File '{file_path}' not found.")
print("Please make sure the file is in the same directory as the script,")
print("or provide the full path to the file.")
# --- Optional: Create a dummy file for testing if it doesn't exist ---
# You can comment this section out if you are sure your file exists
print(f"\nCreating a dummy '{file_path}' for demonstration purposes...")
# Example: 1000 random scores, normally distributed around 0.5, std dev 0.1
dummy_data = np.random.normal(loc=0.5, scale=0.1, size=1000)
dummy_data = np.clip(dummy_data, 0, 1) # Clip scores to be between 0 and 1
np.save(file_path, dummy_data)
print(f"Dummy file '{file_path}' created with 1000 random scores.")
print("Please run the script again to plot the dummy data, or replace it with your actual file.")
# --- End of optional dummy file creation ---
return
# 2. Load the data from the .npy file
try:
data = np.load(file_path)
print(f"Successfully loaded '{file_path}'. Shape: {data.shape}, Data type: {data.dtype}")
except Exception as e:
print(f"Error loading '{file_path}': {e}")
return
# Ensure data is 1D for histogram. If it's multi-dimensional, it will be flattened.
if data.ndim > 1:
print(f"Warning: Data has {data.ndim} dimensions. Flattening to 1D for histogram.")
data = data.flatten()
if data.size == 0:
print("Error: The loaded array is empty. Cannot plot histogram.")
return
# 3. Create the histogram
plt.figure(figsize=(10, 6)) # Set figure size for better readability
# The plt.hist() function returns three values:
# n: the values of the histogram bins
# bins: the edges of the bins
# patches: the individual patches used to create the histogram
n, bins_edges, patches = plt.hist(data, bins=num_bins, color='skyblue', edgecolor='black', alpha=0.7)
print(f"\nHistogram details:")
print(f"Number of data points: {len(data)}")
print(f"Min value: {data.min():.4f}, Max value: {data.max():.4f}, Mean: {data.mean():.4f}")
print(f"Number of bins used: {len(n)}")
# print(f"Bin edges: {bins_edges}") # Uncomment to see bin edges
# print(f"Counts per bin: {n}") # Uncomment to see counts per bin
# 4. Add titles and labels
plt.title(f'Histogram of Scores from {os.path.basename(file_path)}')
plt.xlabel('Score Value')
plt.ylabel('Frequency (Count)')
# 5. Add a grid for better readability
plt.grid(True, linestyle='--', alpha=0.6)
# 6. Show the plot
plt.tight_layout() # Adjust plot to prevent labels from overlapping
plt.show()
if __name__ == "__main__":
plot_histogram_from_npy(FILE_NAME, NUMBER_OF_BINS)
How to use it:
- Save the script: Save the code above as a Python file (e.g.,
plot_scores.py).
- Place your NPY file: Make sure the
sliding_scores-10-pos.npy file is in the same directory as your Python script. If it's elsewhere, you'll need to change the FILE_NAME variable at the top of the script to the full path of your file (e.g., FILE_NAME = '/path/to/your/sliding_scores-10-pos.npy').
- Run the script: Open a terminal or command prompt, navigate to the directory where you saved the script, and run:
python plot_scores.py
A window should pop up displaying the histogram of your scores.
Key features of the script:
- File Check: It checks if the
.npy file exists and provides a helpful message if not.
- Dummy File Creation (Optional): If the specified file is not found, it can create a dummy
.npy file with random data so you can see the script working. You can comment this out if you don't need it.
- Data Loading: Uses
np.load() to read the array.
- Flattening: If your array is multi-dimensional, it will be flattened to 1D, which is what
plt.hist() expects.
- Customizable Bins: You can easily change the
NUMBER_OF_BINS. Using 'auto' lets matplotlib decide a good number of bins.
- Plot Customization: Includes a title, axis labels, and a grid for better visualization.
- Informative Output: Prints some information about the loaded data and histogram to the console.
if __name__ == "__main__":: Ensures the plotting function is called only when the script is executed directly.