### Install Nox using pipx Source: https://github.com/8-hat/plothist/blob/main/docs/CONTRIBUTING.rst Install the Nox automation tool using pipx. Ensure pipx is installed first. ```console pipx install nox ``` -------------------------------- ### Install Development Version using uv Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Set up a virtual environment and install plothist in editable mode with development and test dependencies using uv. ```bash uv sync --group dev --group test ``` -------------------------------- ### Activate Virtual Environment after uv install Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Activate the virtual environment created by uv. This makes the installed package available in your shell. ```bash source .venv/bin/activate ``` -------------------------------- ### Install prek hooks Source: https://github.com/8-hat/plothist/blob/main/docs/CONTRIBUTING.rst Install the prek hooks for managing linters and formatters. This command assumes plothist is installed via uv. ```console uv run prek install ``` -------------------------------- ### Install plothist Locally (Stable) Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Install plothist locally if you lack write access to your virtual environment. This installs the package for the current user. ```bash python3 -m pip install --user plothist ``` -------------------------------- ### Install Fonts on Linux Source: https://github.com/8-hat/plothist/blob/main/docs/documentation/troubleshooting.rst Commands to move and unzip font files to the correct directory on a Linux system. ```bash mv path/to/latinmodern-math.otf ~/.fonts/ unzip -o path/to/latin-modern-roman.zip -d ~/.fonts/latin-modern-roman unzip -o path/to/latin-modern-sans.zip -d ~/.fonts/latin-modern-sans ``` -------------------------------- ### Create and Update Variable Registry Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst This example demonstrates the basic workflow of creating a variable registry, updating binning and custom text, and then using the registry to plot histograms. ```python from plothist import ( make_hist, plot_hist, create_variable_registry, update_variable_registry, update_variable_registry_binning, get_variable_from_registry, add_text, ) import matplotlib.pyplot as plt variable_keys = ["variable_0", "variable_1", "variable_2"] # Create the registry create_variable_registry(variable_keys) # Update the number of bins and range update_variable_registry_binning(df, variable_keys) # Add custom info update_variable_registry({"text": "my analysis"}, variable_keys) for variable_key in variable_keys: # Get the variable information using the key. variable is a dictionary variable = get_variable_from_registry(variable_key) fig, ax = plt.subplots() # Make the histogram using the variable information from the registry h = make_hist(df[variable["name"]], bins=variable["bins"], range=variable["range"]) plot_hist(h, ax=ax) # Get the label and range from the registry ax.set_xlabel(variable["label"]) ax.set_xlim(variable["range"]) ax.set_ylabel("Entries") # Get the custom text from the registry add_text(variable["text"], ax=ax) fig.savefig(f"{variable_key}.pdf", bbox_inches="tight") ``` -------------------------------- ### Install plothist from PyPI (Stable) Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Install the latest stable version of plothist using pip. This command installs the package into your active environment. ```bash python3 -m pip install plothist ``` -------------------------------- ### Updated Variable Registry with Binning and Range Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Example of how the `variable_registry.yaml` file looks after `update_variable_registry_binning` has been called. It shows the automatically calculated bins and range. ```yaml variable_0: name: variable_0 bins: 121 # = len(numpy.histogram_bin_edges(df["variable_0"], bins="auto")) - 1 range: - -10.55227774892869 # min(df["variable_0"]) - 10.04658448558009 # max(df["variable_0"]) label: variable_0 log: false legend_location: best legend_ncols: 1 docstring: '' variable_1: ... ``` -------------------------------- ### Install Development Version without uv Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Install plothist in editable mode with development and test dependencies using pip. Ensure a virtual environment is active. ```bash python3 -m pip install --editable ".[dev,test]" ``` -------------------------------- ### Check Python Version Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Verify your Python 3 version before installation. Requires Python 3.10 or newer. ```bash python3 --version ``` -------------------------------- ### Install Fonts on macOS Source: https://github.com/8-hat/plothist/blob/main/docs/documentation/troubleshooting.rst Commands to move and unzip font files to the correct directory on a macOS system. ```bash mv path/to/latinmodern-math.otf /Users/your_login_username/Library/Fonts/ unzip -o path/to/latin-modern-roman.zip -d /Users/your_login_username/Library/Fonts/latin-modern-roman unzip -o path/to/latin-modern-sans.zip -d /Users/your_login_username/Library/Fonts/latin-modern-sans ``` -------------------------------- ### Unstacked Histograms Comparison Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Presents the same data/model comparison as the stacked example, but with the model represented by unstacked histograms. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_comparison from plothist.plotters import plot_error_hist from plothist.plotters import plot_model from plothist.plotters import add_luminosity import numpy as np import hist def create_hist(name, color, label, nbins=20, start=0, stop=10): return hist.Hist( hist.axis.Regular(nbins, start, stop, name="x", label="x"), name=name, storage=hist.storage.Weight(), ) # Data data = create_hist("data", "black", "Data") data.fill(np.random.normal(5, 1, 10000)) # Model components model_sig = create_hist("sig", "red", "Signal", nbins=20, start=0, stop=10) model_sig.fill(np.random.normal(5, 1.5, 5000)) model_bkg1 = create_hist("bkg1", "blue", "Background 1", nbins=20, start=0, stop=10) model_bkg1.fill(np.random.normal(4, 1, 3000)) model_bkg2 = create_hist("bkg2", "green", "Background 2", nbins=20, start=0, stop=10) model_bkg2.fill(np.random.normal(6, 1.2, 2000)) # Plotting fig, ax = plt.subplots(1, 1, figsize=(8, 6)) plot_data_model_comparison( data_hist=data, unstacked_components=[model_sig, model_bkg1, model_bkg2], plot_kwargs=[ {"color": "red", "label": "Signal"}, {"color": "blue", "label": "Background 1"}, {"color": "green", "label": "Background 2"}, ], ax=ax, ) add_luminosity(ax=ax, text="10 fb$^{-1}") plt.show() ``` -------------------------------- ### Clone plothist Repository Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Clone the plothist repository from GitHub to install the development version. Replace USERNAME with your GitHub username. ```bash git clone git@github.com:USERNAME/plothist.git cd plothist ``` -------------------------------- ### Update plothist to Latest Stable Version Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Update an existing plothist installation to the newest stable release. Use the --upgrade flag with the install command. ```bash python3 -m pip install --upgrade [--user] plothist ``` -------------------------------- ### Getting Comparison Values and Uncertainties Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_hist.rst Retrieve the values, lower uncertainties, and upper uncertainties for a histogram comparison using `get_comparison`. ```python from plothist import get_comparison values, lower_uncertainties, upper_uncertainties = get_comparison(h1, h2, comparison="ratio") ``` -------------------------------- ### Get Variable Information Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Retrieves the plotting information for a specific variable from the registry. ```APIDOC ## Get Variable Information ### Description Retrieves the plotting information for a specific variable from the registry. The information is returned as a dictionary. ### Function Signature `get_variable_from_registry(variable_key: str) -> dict` ### Parameters * **variable_key** (str) - The unique identifier of the variable to retrieve information for. ### Returns * dict - A dictionary containing the plotting information for the specified variable. ### Example ```python from plothist import get_variable_from_registry variable_info = get_variable_from_registry("variable_0") print(variable_info) # Expected output: {'name': 'variable_0', 'bins': 50, 'range': [min, max], 'label': 'variable_0', 'log': False, 'legend_location': 'best', 'legend_ncols': 1, 'docstring': ''} ``` ``` -------------------------------- ### Plot 2D Histogram with Discrete Colormap Source: https://github.com/8-hat/plothist/blob/main/docs/basics/2d_hist.rst Customize the colormap of a 2D histogram using `pcolormesh_kwargs`. This example shows how to apply a discrete colormap. ```python from plothist import make_2d_hist, plot_2d_hist df = get_dummy_data() hist = make_2d_hist(df, "col1", "col2") plot_2d_hist(hist, pcolormesh_kwargs={"cmap": "tab10"}) ``` -------------------------------- ### Plot pyhf Fit Result with plothist Source: https://github.com/8-hat/plothist/blob/main/docs/usage/plot_fitting_results.rst Integrates a pyhf fit result with plothist for visualization. Requires pyhf and plothist libraries. The example shows setting up a model, performing a maximum likelihood fit, and then plotting the data, background, and signal histograms with comparison plots. ```python import pyhf import numpy as np from plothist import make_hist, plot_data_model_comparison pyhf.set_backend("numpy") # Define model data_yield = [100, 50] model = pyhf.simplemodels.uncorrelated_background( signal=[20, 0.0], bkg=[75.0, 50.0], bkg_uncertainty=[np.sqrt(75.0), np.sqrt(50.0)], ) data = data_yield + model.config.auxdata # Maximum likelihood fit bestfit_pars = pyhf.infer.mle.fit(data, model) # Extract fit results model_yields = model.main_model.expected_data(bestfit_pars, return_by_sample=True) bins = [0, 0.5, 1.0] data_hist = make_hist(bins=bins) signal_hist = make_hist(bins=bins) background_hist = make_hist(bins=bins) # Set explicitly the content and variance of each bin. # For the signal and background histograms, we assume no variance. data_hist[:] = np.c_[data_yield, data_yield] background_hist[:] = np.c_[model_yields[0], [0.0, 0.0]] signal_hist[:] = np.c_[model_yields[1], [0.0, 0.0]] fig, ax_main, ax_comparison = plot_data_model_comparison( data_hist=data_hist, stacked_components=[background_hist, signal_hist], stacked_labels=["Background", "Signal"], model_uncertainty=False, xlabel="Variable", ylabel="Entries", comparison="pull", ) ax_main.set_xticks([0, 0.5, 1.0]) ax_main.tick_params(axis="x", which="minor", bottom=False, top=False) ax_comparison.set_xticks([0, 0.5, 1.0]) ax_comparison.tick_params(axis="x", which="minor", bottom=False, top=False) fig.savefig("pyhf.svg", bbox_inches="tight") ``` -------------------------------- ### Get Variable Plotting Information Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Retrieves the plotting configuration dictionary for a specific variable from the registry. This is useful for accessing and using the stored settings. ```python from plothist import get_variable_from_registry variable = get_variable_from_registry("variable_0") print(variable) # {'name': 'variable_0', 'bins': 50, 'range': [min, max], 'label': 'variable_0', 'log': False, 'legend_location': 'best', 'legend_ncols': 1, 'docstring': ''} ``` -------------------------------- ### All Comparisons Without Model Uncertainties Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Similar to the 'All Comparisons' example, but specifically removes model statistical uncertainties by setting `model_uncertainty=False` in `plot_data_model_comparison` and passing a model histogram without uncertainties to `plot_comparison`. ```python from plothist import plot_comparison from plothist.plotters import plot_data_model_comparison from plothist.utils import make_data_model data_hist, model_hist, _ = make_data_model( n_bins=20, model_unc_rel=0.1, model_unc_abs=0.05, data_unc_rel=0.05, data_unc_abs=0.02, seed=0, ) fig, ax = plot_data_model_comparison( data_hist, model_hist, "pull", model_uncertainty=False, plot_kwargs={"label": "Data/Model"}, ) plot_comparison( data_hist, model_hist, "ratio", fig=fig, ax=ax, model_uncertainty=False, plot_kwargs={"label": "Data/Model Ratio"}, ) plot_comparison( data_hist, model_hist, "pull", fig=fig, ax=ax, model_uncertainty=False, plot_kwargs={"label": "Data/Model Pull"}, ) plot_comparison( data_hist, model_hist, "ratio_pull", fig=fig, ax=ax, model_uncertainty=False, plot_kwargs={"label": "Data/Model Ratio Pull"}, ) ``` -------------------------------- ### Get Matplotlib Colormap Colors Source: https://github.com/8-hat/plothist/blob/main/docs/usage/style.rst Generates a list of N colors from any specified Matplotlib colormap. This allows for flexible color selection using established colormaps like 'viridis', 'coolwarm', or 'YlGnBu_r'. ```python from plothist import get_color_palette # From model examples ... background_categories_colors = get_color_palette("Any cmap name", len(background_categories)) ... ``` -------------------------------- ### Get Cubehelix Color Palette Source: https://github.com/8-hat/plothist/blob/main/docs/usage/style.rst Retrieves the cubehelix color palette, recommended for displaying quantities like yields or intensities due to its perceptual uniformity. This function is adapted from seaborn. ```python from plothist import get_color_palette colors = get_color_palette("cubehelix", 7) ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/8-hat/plothist/blob/main/docs/usage/installation.rst Set up an isolated Python environment for plothist. This is an optional but recommended step. ```bash python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Create Variable Registry Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Initializes a `variable_registry.yaml` file with default plotting information for the specified variable keys. Use this to set up the registry for new projects or to add variables. ```python from plothist import create_variable_registry variable_keys = ["variable_0", "variable_1", "variable_2"] create_variable_registry(variable_keys) ``` -------------------------------- ### Creating and Plotting a Mean Histogram (Profile Plot) Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_hist.rst Demonstrates how to create a mean histogram (profile plot) using boost-histogram and visualize it with plothist. Each bin shows the average value and standard deviation. ```python from plothist import make_hist import numpy as np data = np.random.normal(size=1000) # Create a mean histogram where each bin stores the mean and std of the data in that bin h_mean = make_hist(data, bins=10, is_mean=True) # Plotting a mean histogram # Note: Most plothist functions only work with counting histograms. # This example is for demonstration of mean histogram creation and plotting. h_mean.plot() ``` -------------------------------- ### Create Variable Registry Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Initializes a variable registry by creating a `variable_registry.yaml` file with default information for the specified variable keys. ```APIDOC ## Create Variable Registry ### Description Initializes a variable registry by creating a `variable_registry.yaml` file with default information for the specified variable keys. If the file already exists, new variables are added without overwriting existing ones, unless `reset` is set to `True`. ### Function Signature `create_variable_registry(variable_keys: list, reset: bool = False)` ### Parameters * **variable_keys** (list) - A list of strings, where each string is a unique identifier for a variable. * **reset** (bool, optional) - If `True`, existing entries in the registry will be overwritten. Defaults to `False`. ### Example ```python from plothist import create_variable_registry variable_keys = ["variable_0", "variable_1", "variable_2"] create_variable_registry(variable_keys) ``` ``` -------------------------------- ### Create Font Directory Source: https://github.com/8-hat/plothist/blob/main/docs/documentation/troubleshooting.rst Use these commands to create the necessary font directories on Linux or macOS if they do not already exist. ```bash mkdir ~/.fonts # for Linux mkdir /Users/your_login_username/Library/Fonts # for MacOS ``` -------------------------------- ### List available Nox sessions Source: https://github.com/8-hat/plothist/blob/main/docs/CONTRIBUTING.rst Display all the available sessions that can be run with Nox. ```console nox -l ``` -------------------------------- ### Run specific Nox sessions Source: https://github.com/8-hat/plothist/blob/main/docs/CONTRIBUTING.rst Execute specific Nox sessions like 'lint', 'tests', or 'docs'. Use '--' to pass arguments to the session. ```console nox -s lint ``` ```console nox -s tests ``` ```console nox -s docs ``` ```console nox -s docs --non-interactive ``` ```console nox -s docs -- -b linkcheck ``` ```console nox -s coverage ``` ```console nox -s generate_examples_figures -- tests/test_examples_*.py ``` -------------------------------- ### Clear Matplotlib Font Cache Source: https://github.com/8-hat/plothist/blob/main/docs/documentation/troubleshooting.rst This Python script finds and removes matplotlib's font cache files, which is often necessary after installing new fonts. ```python import matplotlib import subprocess from pathlib import PosixPath cache_files = PosixPath(matplotlib.get_cachedir()).glob("fontlist-v???.json") for cache_file in cache_files: subprocess.run(["rm", "-v", cache_file]) ``` -------------------------------- ### Model Uncertainty Comparison using Pulls Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Demonstrates comparing data and model histograms using the 'pull' method instead of the default ratio. This is useful for visualizing deviations. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_comparison from plothist.plotters import plot_error_hist from plothist.plotters import plot_model from plothist.plotters import add_luminosity import numpy as np import hist def create_hist(name, color, label, nbins=20, start=0, stop=10): return hist.Hist( hist.axis.Regular(nbins, start, stop, name="x", label="x"), name=name, storage=hist.storage.Weight(), ) # Data data = create_hist("data", "black", "Data") data.fill(np.random.normal(5, 1, 10000)) # Model components model_sig = create_hist("sig", "red", "Signal", nbins=20, start=0, stop=10) model_sig.fill(np.random.normal(5, 1.5, 5000)) model_bkg1 = create_hist("bkg1", "blue", "Background 1", nbins=20, start=0, stop=10) model_bkg1.fill(np.random.normal(4, 1, 3000)) model_bkg2 = create_hist("bkg2", "green", "Background 2", nbins=20, start=0, stop=10) model_bkg2.fill(np.random.normal(6, 1.2, 2000)) # Plotting fig, ax = plt.subplots(1, 1, figsize=(8, 6)) plot_data_model_comparison( data_hist=data, stacked_components=[model_sig, model_bkg1, model_bkg2], comparison_method=plot_comparison.pull, plot_kwargs=[ {"color": "red", "label": "Signal"}, {"color": "blue", "label": "Background 1"}, {"color": "green", "label": "Background 2"}, ], ax=ax, ) add_luminosity(ax=ax, text="10 fb$^{-1}") plt.show() ``` -------------------------------- ### Run Nox for linting and testing Source: https://github.com/8-hat/plothist/blob/main/docs/CONTRIBUTING.rst Execute Nox to automatically lint and test the project across multiple Python versions. This command runs all defined sessions. ```console nox ``` -------------------------------- ### Get Default ggplot Color Palette Source: https://github.com/8-hat/plothist/blob/main/docs/usage/style.rst Retrieves the default color palette used by plothist, adapted from ggplot. This is useful for consistent plotting when no specific colors are provided. ```python from plothist import get_color_palette colors = get_color_palette("ggplot", 7) print(colors) # ['#348ABD','#E24A33', '#988ED5', '#777777', '#FBC15E', '#8EBA42', '#FFB5B8'] ``` -------------------------------- ### Create data and model histograms Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Generates data, signal, and background histograms from a DataFrame using specified masks and categories. Includes optional scaling of model histograms to match data counts. ```python from plothist import make_hist, get_color_palette from scipy.stats import norm key = "variable_1" range = (-9, 12) category = "category" # Define some masks to separate the dataset in signal (1 category), background (3 categories) and data (1 category) signal_mask = df[category] == 7 data_mask = df[category] == 8 background_categories = [0, 1, 2] background_categories_labels = [f"c{i}" for i in background_categories] background_categories_colors = get_color_palette("cubehelix", len(background_categories)) background_masks = [df[category] == p for p in background_categories] # Create the histograms using the masks defined above data_hist = make_hist(df[key][data_mask], bins=50, range=range, weights=1) background_hists = [make_hist(df[key][mask], bins=50, range=range, weights=1) for mask in background_masks] signal_hist = make_hist(df[key][signal_mask], bins=50, range=range, weights=1) # Optional: scale to data # boost_histogram.Histogram objects are easy to manipulate. # Here, we multiply them by a scalar to scale them, and their variance is correctly scaled as well. background_scaling_factor = data_hist.sum().value / sum(background_hists).sum().value background_hists = [background_scaling_factor * h for h in background_hists] signal_scaling_factor = data_hist.sum().value / signal_hist.sum().value signal_hist *= signal_scaling_factor # Define some random functions that will be used as model components with functions def f_signal(x): return 1000 * norm.pdf(x, loc=0.5, scale=3) def f_background1(x): return 1000 * norm.pdf(x, loc=-1.5, scale=4) def f_background2(x): return 3000 * norm.pdf(x, loc=-1.8, scale=1.8) ``` -------------------------------- ### Plot 1D Histogram with String Categories Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_hist.rst Demonstrates how to create and plot a 1D histogram with string categories. Ensure you are using weighted storage, which is the default for make_hist. ```python import plothist import numpy as np hist = plothist.histogramming.make_hist( plothist.axis.StrCategory(name="cat", categories=["A", "B", "C"]), name="My histogram" ) hist.fill(np.random.choice(["A", "B", "C"], size=1000)) plothist.plotters.plot_hist(hist) # Save the plot # import matplotlib.pyplot as plt # plt.savefig("1d_str_category.png") ``` -------------------------------- ### Plot a Simple Function Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_func.rst Use plot_function() to visualize a mathematical function. Ensure you have the necessary data loaded. ```python from plothist.plotters import plot_function plot_function(df, "x", "y") ``` -------------------------------- ### Update Binning and Range Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Automatically updates the `bins` and `range` parameters in the `variable_registry.yaml` file based on the provided dataset (`df`). It calculates optimal bins and range from the data. Use `overwrite=True` to force updates on existing entries. ```python from plothist import update_variable_registry_binning update_variable_registry_binning(df, variable_keys) ``` -------------------------------- ### Load Dummy Data for Plotting Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_func.rst This code imports a utility function to load dummy data, which can be used as a numpy ndarray or a pandas dataframe for plotting. ```python from plothist_utils import get_dummy_data df = get_dummy_data() ``` -------------------------------- ### Renormalize PDF for Plotting Source: https://github.com/8-hat/plothist/blob/main/docs/usage/plot_fitting_results.rst Renormalizes a PDF to match the number of expected data events, considering bin width and integral. Assumes regular binning. ```python from scipy.integrate import quad def renormalize(pdf, x_range, n_bins, n_data): """ Renormalize a PDF to its corresponding number of data events. Parameters ---------- pdf : callable The PDF to renormalize. x_range : tuple The range of the PDF. n_bins : int The number of bins. Regular binning is assumed. n_data : int The number of predicted data events in the x_range associated to the pdf. Returns ------- pdf : callable The renormalized PDF. """ xmin, xmax = x_range bin_width = (xmax - xmin) / n_bins integral = quad(pdf, xmin, xmax)[0] # Note: If x_range is equal to the full range of the PDF, the integral is equal to 1. def renormalized_pdf(x): return pdf(x) * n_data * bin_width / integral return renormalized_pdf ``` -------------------------------- ### Variable Registry After Adding Properties Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Illustrates the `variable_registry.yaml` file after using `update_variable_registry` to add custom properties. New keys and their values are appended to the variable entries. ```yaml ``` -------------------------------- ### Model with Stacked and Unstacked Function Components Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Compares data to a model constructed from both stacked and unstacked functions. All functions contribute to the total model sum. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_comparison from plothist.plotters import plot_error_hist from plothist.plotters import plot_model from plothist.plotters import add_luminosity import numpy as np import hist def create_hist(name, color, label, nbins=20, start=0, stop=10): return hist.Hist( hist.axis.Regular(nbins, start, stop, name="x", label="x"), name=name, storage=hist.storage.Weight(), ) def create_func(name, color, label, nbins=20, start=0, stop=10): return hist.Hist( hist.axis.Regular(nbins, start, stop, name="x", label="x"), name=name, storage=hist.storage.Weight(), ) # Data data = create_hist("data", "black", "Data") data.fill(np.random.normal(5, 1, 10000)) # Model components (functions) model_func_stacked1 = create_func("func_stacked1", "red", "Function Stacked 1") model_func_stacked1.fill(np.random.normal(5, 1.5, 5000)) model_func_stacked2 = create_func("func_stacked2", "blue", "Function Stacked 2") model_func_stacked2.fill(np.random.normal(4, 1, 3000)) model_func_unstacked = create_func("func_unstacked", "green", "Function Unstacked") model_func_unstacked.fill(np.random.normal(6, 1.2, 2000)) # Plotting fig, ax = plt.subplots(1, 1, figsize=(8, 6)) plot_data_model_comparison( data_hist=data, stacked_components=[model_func_stacked1, model_func_stacked2], unstacked_components=[model_func_unstacked], plot_kwargs=[ {"color": "red", "label": "Function Stacked 1"}, {"color": "blue", "label": "Function Stacked 2"}, {"color": "green", "label": "Function Unstacked"}, ], ax=ax, ) add_luminosity(ax=ax, text="10 fb$^{-1}") plt.show() ``` -------------------------------- ### Creating and Plotting a 1D Histogram with Integer Category Axis Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_hist.rst Shows how to create and plot a 1D histogram with an integer category axis using boost-histogram and plothist. ```python from plothist import make_hist import numpy as np # Example data with integer categories data = np.random.randint(0, 5, size=1000) # Create a histogram with an integer category axis h_cat = make_hist(data, axis_type='int_category', name='Category') h_cat.plot() ``` -------------------------------- ### Plot Stacked Functions Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_func.rst Visualize multiple functions stacked on top of each other by setting the 'stacked' argument to True. This is useful for comparing distributions. ```python from plothist.plotters import plot_function plot_function(df, "x", "y", stacked=True) ``` -------------------------------- ### Stacked and Unstacked Histograms Comparison Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Combines stacked and unstacked histograms to form the model. The sum of all components, regardless of stacking, defines the total model. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_comparison from plothist.plotters import plot_error_hist from plothist.plotters import plot_model from plothist.plotters import add_luminosity import numpy as np import hist def create_hist(name, color, label, nbins=20, start=0, stop=10): return hist.Hist( hist.axis.Regular(nbins, start, stop, name="x", label="x"), name=name, storage=hist.storage.Weight(), ) # Data data = create_hist("data", "black", "Data") data.fill(np.random.normal(5, 1, 10000)) # Model components model_sig_stacked = create_hist("sig_stacked", "red", "Signal Stacked", nbins=20, start=0, stop=10) model_sig_stacked.fill(np.random.normal(5, 1.5, 5000)) model_bkg1_stacked = create_hist("bkg1_stacked", "blue", "Background 1 Stacked", nbins=20, start=0, stop=10) model_bkg1_stacked.fill(np.random.normal(4, 1, 3000)) model_unstacked = create_hist("bkg_unstacked", "green", "Background Unstacked", nbins=20, start=0, stop=10) model_unstacked.fill(np.random.normal(6, 1.2, 2000)) # Plotting fig, ax = plt.subplots(1, 1, figsize=(8, 6)) plot_data_model_comparison( data_hist=data, stacked_components=[model_sig_stacked, model_bkg1_stacked], unstacked_components=[model_unstacked], plot_kwargs=[ {"color": "red", "label": "Signal Stacked"}, {"color": "blue", "label": "Background 1 Stacked"}, {"color": "green", "label": "Background Unstacked"}, ], ax=ax, ) add_luminosity(ax=ax, text="10 fb$^{-1}") plt.show() ``` -------------------------------- ### Plotting with Different Variable Keys Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst This Python code snippet illustrates how to iterate through a list of variable keys, retrieve their corresponding registry information, and use it to plot histograms, including custom zoomed versions. ```python variable_keys = ["variable_0", "variable_0_zoom", "variable_1"] for variable_key in variable_keys: variable = get_variable_from_registry(variable_key) ... ``` -------------------------------- ### Plot model with stacked and unstacked functions Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Visualize a model composed of stacked and unstacked functions. The total sum represents the combined output of all function components. ```python ### from plothist import make_hist, get_color_palette, plot_model from scipy.stats import norm key = "variable_1" range = (-9, 12) category = "category" # Define some masks to separate the dataset in signal (1 category), background (3 categories) and data (1 category) signal_mask = df[category] == 7 data_mask = df[category] == 8 background_categories = [0, 1, 2] background_categories_labels = [f"c{i}" for i in background_categories] background_categories_colors = get_color_palette("cubehelix", len(background_categories)) background_masks = [df[category] == p for p in background_categories] # Create the histograms using the masks defined above data_hist = make_hist(df[key][data_mask], bins=50, range=range, weights=1) background_hists = [make_hist(df[key][mask], bins=50, range=range, weights=1) for mask in background_masks] signal_hist = make_hist(df[key][signal_mask], bins=50, range=range, weights=1) # Optional: scale to data # boost_histogram.Histogram objects are easy to manipulate. # Here, we multiply them by a scalar to scale them, and their variance is correctly scaled as well. background_scaling_factor = data_hist.sum().value / sum(background_hists).sum().value background_hists = [background_scaling_factor * h for h in background_hists] signal_scaling_factor = data_hist.sum().value / signal_hist.sum().value signal_hist *= signal_scaling_factor # Define some random functions that will be used as model components with functions def f_signal(x): return 1000 * norm.pdf(x, loc=0.5, scale=3) def f_background1(x): return 1000 * norm.pdf(x, loc=-1.5, scale=4) def f_background2(x): return 3000 * norm.pdf(x, loc=-1.8, scale=1.8) # Plotting plot_model( [ f_background1, f_background2, f_signal, ], stacked=True, labels=["background 1", "background 2", "signal"], colors=["red", "orange", "purple"], unstacked_functions=[ f_background1 # Example of unstacked function ], unstacked_labels=["unstacked background 1"], unstacked_colors=["darkblue"], title="Model with stacked and unstacked functions" ) ``` -------------------------------- ### Extract and Interpolate TGraphs from ROOT File Source: https://github.com/8-hat/plothist/blob/main/docs/usage/plot_fitting_results.rst Iterates through ROOT primitives, extracts TGraph objects (excluding TGraphAsymmErrors), interpolates their data into functions using interp1d, and stores the function names and interpolated functions in separate lists. Assumes no variance for signal and background histograms. ```python for obj in canvas.GetListOfPrimitives(): if isinstance(obj, ROOT.TGraph) and not isinstance(obj, ROOT.TGraphAsymmErrors): # Get the x and y values of the TGraph pdf_names.append(obj.GetName()) x_values = obj.GetX() y_values = obj.GetY() # Interpolate the TGraph to get a function pdf_func = interp1d(x_values, y_values) pdf_list.append(pdf_func) print(f"\nPDFs from {root_file_name} saved in the list:") for k_name, pdf_name in enumerate(pdf_names): print(f"\t[{k_name}] {pdf_name}") print() return pdf_list ``` -------------------------------- ### Stacked Histograms Comparison Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Compares data to a model composed of 3 stacked histograms. A separate signal histogram is also plotted but not included in the comparison. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_comparison from plothist.plotters import plot_error_hist from plothist.plotters import plot_model from plothist.plotters import add_luminosity import numpy as np import hist def create_hist(name, color, label, nbins=20, start=0, stop=10): return hist.Hist( hist.axis.Regular(nbins, start, stop, name="x", label="x"), name=name, storage=hist.storage.Weight(), ) # Data data = create_hist("data", "black", "Data") data.fill(np.random.normal(5, 1, 10000)) # Model components model_sig = create_hist("sig", "red", "Signal", nbins=20, start=0, stop=10) model_sig.fill(np.random.normal(5, 1.5, 5000)) model_bkg1 = create_hist("bkg1", "blue", "Background 1", nbins=20, start=0, stop=10) model_bkg1.fill(np.random.normal(4, 1, 3000)) model_bkg2 = create_hist("bkg2", "green", "Background 2", nbins=20, start=0, stop=10) model_bkg2.fill(np.random.normal(6, 1.2, 2000)) # Plotting fig, ax = plt.subplots(1, 1, figsize=(8, 6)) plot_data_model_comparison( data_hist=data, stacked_components=[model_sig, model_bkg1, model_bkg2], plot_kwargs=[ {"color": "red", "label": "Signal"}, {"color": "blue", "label": "Background 1"}, {"color": "green", "label": "Background 2"}, ], ax=ax, ) add_luminosity(ax=ax, text="10 fb$^{-1}") plt.show() ``` -------------------------------- ### Update Binning and Ranges Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst Automatically updates the binning and range parameters for specified variables in the registry based on the provided dataset. ```APIDOC ## Update Binning and Ranges ### Description Automatically updates the number of bins and the range parameters for specified variables in the registry based on the provided dataset. The `bins` parameter is set to the number of bins determined by `numpy.histogram_bin_edges`, and the `range` parameter is set to the minimum and maximum values of the variable in the dataset. This update can be optionally overwritten. ### Function Signature `update_variable_registry_binning(df: pd.DataFrame, variable_keys: list, overwrite: bool = False)` ### Parameters * **df** (pd.DataFrame) - The pandas DataFrame containing the data. * **variable_keys** (list) - A list of variable keys (strings) for which to update binning and range information. * **overwrite** (bool, optional) - If `True`, existing `bins` and `range` values in the registry will be overwritten. Defaults to `False`. ### Example ```python from plothist import update_variable_registry_binning import pandas as pd # Assuming 'df' is a pandas DataFrame with columns 'variable_0', 'variable_1' # df = pd.DataFrame(...) variable_keys_to_update = ["variable_0", "variable_1"] update_variable_registry_binning(df, variable_keys_to_update) ``` ``` -------------------------------- ### Plot a simple 1D histogram Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_hist.rst Creates and plots a simple 1D histogram using make_hist and plot_hist. The make_hist function creates a histogram object, and plot_hist visualizes it. ```python from plothist import make_hist, plot_hist from plothist_utils import get_dummy_data df = get_dummy_data() hist = make_hist(df.values) plot_hist(hist) ``` -------------------------------- ### Define Variable Registry with Zoomed Range Source: https://github.com/8-hat/plothist/blob/main/docs/basics/variable_registry.rst This YAML configuration shows how to define a variable with a standard range and a 'zoom' version of the same variable with a more restricted range for plotting. ```yaml variable_0: name: variable_0 bins: 121 range: - -10 - 10 label: $Variable_{0}$ log: false legend_location: best legend_ncols: 1 docstring: '' variable_0_zoom: name: variable_0 bins: 121 range: - -1 - 1 label: $Zoom of Variable_{0}$ log: false legend_location: upper right legend_ncols: 1 docstring: '' variable_1: ... ``` -------------------------------- ### Save RooFit PDF as Scipy Interpolation Function Source: https://github.com/8-hat/plothist/blob/main/docs/usage/plot_fitting_results.rst Converts a RooFit PDF object into a scipy.interpolate.interp1d function for easier use with other libraries. This function evaluates the PDF at many points and interpolates the results. It requires RooFit, numpy, scipy, and pickle. Ensure correct PDF projection for complex models. ```python import numpy as np from scipy.interpolate import interp1d import pickle def save_pdf(var, pdf, path="pdf.pkl", n_points=10000): """ Save a RooFit PDF as a scipy.interpolate.interp1d function. Parameters ---------- var : RooRealVar The variable to evaluate the PDF at. pdf : RooAbsPdf The PDF to save. path : str, optional The path to save the PDF to. Should end with `.pkl`. Default is "pdf.pkl". n_points : int, optional The number of points to evaluate the PDF at. Default is 10000. Returns ------- pdf_func : scipy.interpolate.interp1d The PDF as a function. Notes ----- The PDF is saved as a scipy.interpolate.interp1d function with pickle. """ pdf_x = np.zeros(n_points) xlim = (var.getMin(), var.getMax()) # Get a sample of x values x = np.linspace(*xlim, n_points) for i in range(len(x)): var.setVal(x[i]) # Evaluate the PDF at the given x value pdf_x[i] = pdf.getVal(var) # Interpolate the PDF pdf_func = interp1d(x, pdf_x) with open(path, "wb") as f: print(f"Saving model to {f.name}") pickle.dump(pdf_func, f) return pdf_func ``` -------------------------------- ### All Comparisons Between Data and Model Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Generates a plot showing all possible comparisons between data and model. It uses `plot_data_model_comparison` for the ratio and `plot_comparison` to add other comparison types to the same figure. ```python from plothist import plot_comparison from plothist.plotters import plot_data_model_comparison from plothist.utils import make_data_model data_hist, model_hist, _ = make_data_model( n_bins=20, model_unc_rel=0.1, model_unc_abs=0.05, data_unc_rel=0.05, data_unc_abs=0.02, seed=0, ) fig, ax = plot_data_model_comparison( data_hist, model_hist, "pull", plot_kwargs={"label": "Data/Model"}, ) plot_comparison( data_hist, model_hist, "ratio", fig=fig, ax=ax, plot_kwargs={"label": "Data/Model Ratio"} ) plot_comparison( data_hist, model_hist, "pull", fig=fig, ax=ax, plot_kwargs={"label": "Data/Model Pull"} ) plot_comparison( data_hist, model_hist, "ratio_pull", fig=fig, ax=ax, plot_kwargs={"label": "Data/Model Ratio Pull"} ) ``` -------------------------------- ### Plot model with stacked and unstacked histograms Source: https://github.com/8-hat/plothist/blob/main/docs/advanced/model_examples.rst Visualize a model composed of both stacked and unstacked histograms. The total sum represents the combined count of all components. ```python ### from plothist import make_hist, get_color_palette, plot_model from scipy.stats import norm key = "variable_1" range = (-9, 12) category = "category" # Define some masks to separate the dataset in signal (1 category), background (3 categories) and data (1 category) signal_mask = df[category] == 7 data_mask = df[category] == 8 background_categories = [0, 1, 2] background_categories_labels = [f"c{i}" for i in background_categories] background_categories_colors = get_color_palette("cubehelix", len(background_categories)) background_masks = [df[category] == p for p in background_categories] # Create the histograms using the masks defined above data_hist = make_hist(df[key][data_mask], bins=50, range=range, weights=1) background_hists = [make_hist(df[key][mask], bins=50, range=range, weights=1) for mask in background_masks] signal_hist = make_hist(df[key][signal_mask], bins=50, range=range, weights=1) # Optional: scale to data # boost_histogram.Histogram objects are easy to manipulate. # Here, we multiply them by a scalar to scale them, and their variance is correctly scaled as well. background_scaling_factor = data_hist.sum().value / sum(background_hists).sum().value background_hists = [background_scaling_factor * h for h in background_hists] signal_scaling_factor = data_hist.sum().value / signal_hist.sum().value signal_hist *= signal_scaling_factor # Define some random functions that will be used as model components with functions def f_signal(x): return 1000 * norm.pdf(x, loc=0.5, scale=3) def f_background1(x): return 1000 * norm.pdf(x, loc=-1.5, scale=4) def f_background2(x): return 3000 * norm.pdf(x, loc=-1.8, scale=1.8) # Plotting plot_model( [ background_hists[0], background_hists[1], background_hists[2], signal_hist, ], stacked=True, labels=["background 1", "background 2", "background 3", "signal"], colors=["red", "orange", "lightblue", "purple"], unstacked_histograms=[ background_hists[0] # Example of unstacked histogram ], unstacked_labels=["unstacked background 1"], unstacked_colors=["darkblue"], title="Model with stacked and unstacked histograms" ) ``` -------------------------------- ### Compare two histograms using split ratio Source: https://github.com/8-hat/plothist/blob/main/docs/basics/1d_hist.rst Compares two histograms using the 'split_ratio' method, which scales uncertainties and displays them separately. This is often used when comparing measured data to a model. ```python from plothist import make_hist, plot_two_hist_comparison from plothist_utils import get_dummy_data df = get_dummy_data() hist1 = make_hist(df.values) hist2 = make_hist(df.values * 2) plot_two_hist_comparison(hist1, hist2, comparison_method='split_ratio') ```