Of course! Here is a complete and well-documented Python script to generate a bar chart from metrics in multiple YAML files.
This script uses pandas for easy data manipulation and seaborn for creating an aesthetically pleasing plot. It's designed to be run from the command line.
Key Features:
Command-line Interface: Takes a list of YAML files and an optional output file name as arguments.
Automatic Model Naming: Uses the YAML filenames (without the extension) as model names in the chart.
Data Aggregation: Collects all metrics from all files into a single structure for easy plotting.
Pretty Plotting: Uses seaborn for a clean look, adds value labels on top of the bars, and includes a clear legend.
Error Handling: Includes basic checks for file existence.
1. Prerequisites
You'll need to install the required Python libraries. You can do this using pip:
bash
pip install pyyaml pandas seaborn matplotlib
2. Example YAML Files
Let's create two example YAML files to test the script.
#!/usr/bin/env python3
import argparse
import os
import yaml
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def parse_yaml_files(file_paths: list[str]) -> pd.DataFrame:
"""
Parses a list of YAML files and organizes the data into a pandas DataFrame.
Args:
file_paths: A list of paths to the YAML files.
Returns:
A pandas DataFrame with columns ['model', 'metric', 'value'],
ready for plotting.
"""
all_metrics_data = []
for file_path in file_paths:
# Use filename (without extension) as the model name
model_name = os.path.splitext(os.path.basename(file_path))[0]
try:
with open(file_path, 'r') as f:
metrics = yaml.safe_load(f)
if not isinstance(metrics, dict):
print(f"Warning: Content of {file_path} is not a dictionary. Skipping.")
continue
for metric_name, value in metrics.items():
all_metrics_data.append({
'model': model_name,
'metric': metric_name,
'value': float(value) # Ensure value is a number
})
except FileNotFoundError:
print(f"Error: File not found at {file_path}. Skipping.")
except yaml.YAMLError as e:
print(f"Error parsing YAML file {file_path}: {e}. Skipping.")
except Exception as e:
print(f"An unexpected error occurred with file {file_path}: {e}. Skipping.")
if not all_metrics_data:
print("Error: No valid data was loaded. Exiting.")
exit(1)
return pd.DataFrame(all_metrics_data)
def plot_bar_chart(df: pd.DataFrame, output_filename: str):
"""
Generates and saves a styled bar chart from the metrics DataFrame.
Args:
df: DataFrame containing the metric data.
output_filename: The path to save the output PNG image.
"""
if df.empty:
print("Cannot plot an empty dataframe.")
return
# Set a nice theme for the plot
sns.set_theme(style="whitegrid")
# Determine plot dimensions
num_metrics = len(df['metric'].unique())
num_models = len(df['model'].unique())
fig_width = max(8, num_metrics * num_models * 0.8)
fig_height = 6
# Create the plot
fig, ax = plt.subplots(figsize=(fig_width, fig_height))
# Use seaborn to create the bar plot
sns.barplot(data=df, x='metric', y='value', hue='model', ax=ax, palette='viridis')
# --- Prettify the Plot ---
# Add value labels on top of each bar
for container in ax.containers:
ax.bar_label(container, fmt='%.3f', fontsize=10, padding=3)
# Set title and labels with improved font sizes
ax.set_title('Model Performance Comparison', fontsize=16, weight='bold', pad=20)
ax.set_xlabel('Metric', fontsize=12)
ax.set_ylabel('Score', fontsize=12)
# Adjust y-axis limits to give space for labels on top
# This prevents labels from being cut off
current_ylim = ax.get_ylim()
ax.set_ylim(0, current_ylim[1] * 1.15)
# Rotate x-axis labels if they are long to prevent overlap
plt.xticks(rotation=15, ha='right')
# Improve the legend
ax.legend(title='Model', bbox_to_anchor=(1.02, 1), loc='upper left')
# Adjust layout to make sure everything fits without overlapping
plt.tight_layout(rect=[0, 0, 0.9, 1]) # Adjust rect to make space for legend
# Save the figure
try:
plt.savefig(output_filename, dpi=300, bbox_inches='tight')
print(f"✓ Chart successfully saved to {output_filename}")
except Exception as e:
print(f"Error saving the plot: {e}")
def main():
"""Main function to parse arguments and run the script."""
parser = argparse.ArgumentParser(
description="Generate a bar chart comparing metrics from multiple YAML files.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
'yaml_files',
metavar='FILE',
nargs='+', # Accepts one or more file paths
help="One or more YAML files containing model metrics."
)
parser.add_argument(
'-o', '--output',
dest='output_file',
default='metrics_comparison.png',
help="Path to save the output PNG image (default: metrics_comparison.png)"
)
args = parser.parse_args()
# 1. Parse YAML files into a DataFrame
metrics_df = parse_yaml_files(args.yaml_files)
# 2. Generate and save the plot
plot_bar_chart(metrics_df, args.output_file)
if __name__ == '__main__':
main()
4. How to Run the Script
Make sure plot_metrics.py, model_A.yaml, and model_B.yaml are in the same directory.
Open your terminal or command prompt.
Run the script by providing the YAML files as arguments: