plot_whisker.py
This file
Path
scripts/plot_whisker.py
73 lines · 2.3 KiB · Python
Last changed by
Support all exported metrics in plotting scripts (#981)David Peterbefore adoptionef86c83
History of this fileTake it
1#!/usr/bin/env python2# /// script3# requires-python = ">=3.10"4# dependencies = [5# "matplotlib",6# "pyqt6",7# ]8# ///910"""This program shows `hyperfine` benchmark results as a box and whisker plot.1112Quoting from the matplotlib documentation:13 The box extends from the lower to upper quartile values of the data, with14 a line at the median. The whiskers extend from the box to show the range15 of the data. Flier points are those past the end of the whiskers.16"""1718import argparse19import json2021import matplotlib.pyplot as plt2223from plot_utils import METRICS, add_metric_argument, validate_metric2425parser = argparse.ArgumentParser(description=__doc__)26add_metric_argument(parser)27parser.add_argument("file", help="JSON file with benchmark results")28parser.add_argument("--title", help="Plot Title")29parser.add_argument("--sort-by", choices=["median"], help="Sort method")30parser.add_argument(31 "--labels", help="Comma-separated list of entries for the plot legend"32)33parser.add_argument("-o", "--output", help="Save image to the given filename.")3435args = parser.parse_args()36metric_label, metric_scale = METRICS[args.metric]3738with open(args.file, encoding="utf-8") as f:39 results = json.load(f)["results"]40validate_metric(parser, results, args.metric)4142if args.labels:43 labels = args.labels.split(",")44else:45 labels = [b.get("name", b["command"]) for b in results]46values = [47 [m[args.metric]["value"] / metric_scale for m in b["measurements"]] for b in results48]4950if args.sort_by == "median":51 medians = [b["summary"][args.metric]["median"] for b in results]52 indices = sorted(range(len(labels)), key=lambda k: medians[k])53 labels = [labels[i] for i in indices]54 values = [values[i] for i in indices]5556plt.figure(figsize=(10, 6), constrained_layout=True)57boxplot = plt.boxplot(values, vert=True, patch_artist=True)58cmap = plt.get_cmap("rainbow")59colors = [cmap(val / len(values)) for val in range(len(values))]6061for patch, color in zip(boxplot["boxes"], colors):62 patch.set_facecolor(color)6364if args.title:65 plt.title(args.title)66plt.legend(handles=boxplot["boxes"], labels=labels, loc="best", fontsize="medium")67plt.ylabel(metric_label)68plt.ylim(0, None)69plt.xticks(list(range(1, len(labels) + 1)), labels, rotation=45)70if args.output:71 plt.savefig(args.output)72else:73 plt.show()