### Install nox using pipx Source: https://plothist.readthedocs.io/en/latest/_sources/CONTRIBUTING.rst.txt Install the nox automation tool using pipx. Ensure pipx is installed first. ```console pipx install nox ``` -------------------------------- ### Install Pre-commit Hooks Source: https://plothist.readthedocs.io/en/latest/CONTRIBUTING.html Install the pre-commit hooks managed by prek. This ensures code quality checks are performed before committing. ```bash uv run prek install ``` -------------------------------- ### Install Plothist from PyPI (User) Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Install plothist for the current user only, useful if you lack write access to the virtual environment directory. This installs the package locally. ```bash python3 -m pip install --user plothist ``` -------------------------------- ### Install Nox Source: https://plothist.readthedocs.io/en/latest/CONTRIBUTING.html Install nox using pipx. This is a prerequisite for managing development tasks. ```bash pipx install nox ``` -------------------------------- ### Install Development Version using uv Source: https://plothist.readthedocs.io/en/latest/usage/installation.html Installs plothist in editable mode with development and test dependencies using `uv`. Assumes `uv` is installed and the repository is cloned. ```bash uv sync --group dev --group test ``` -------------------------------- ### Install Development Version using uv Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Set up a virtual environment and install plothist in editable mode with development and test dependencies using the 'uv' package manager. ```bash uv sync --group dev --group test ``` -------------------------------- ### Activate Virtual Environment after uv install Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Activate the virtual environment created by 'uv sync' to use the installed development version of plothist. ```bash source .venv/bin/activate ``` -------------------------------- ### Install prek hooks Source: https://plothist.readthedocs.io/en/latest/_sources/CONTRIBUTING.rst.txt 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://plothist.readthedocs.io/en/latest/usage/installation.html Installs plothist locally if you lack write access to the virtual environment directory. Ensure your environment is activated first. ```bash python3 -m pip install --user plothist ``` -------------------------------- ### Create Font Directory on Linux Source: https://plothist.readthedocs.io/en/latest/_sources/documentation/troubleshooting.rst.txt Use this command to create the .fonts directory on Linux if it does not exist. This is a prerequisite for manual font installation. ```bash mkdir ~/.fonts # for Linux ``` -------------------------------- ### Get Dummy Data for plothist Source: https://plothist.readthedocs.io/en/latest/_sources/advanced/other_advanced.rst.txt Loads dummy data for use with plothist. This is a common starting point for examples. ```python from plothist_utils import get_dummy_data df = get_dummy_data() ``` -------------------------------- ### Install Plothist from PyPI (Standard) Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Install the latest stable version of plothist from the Python Package Index (PyPI). This command should be run within an activated virtual environment. ```bash python3 -m pip install plothist ``` -------------------------------- ### Install Development Version without uv Source: https://plothist.readthedocs.io/en/latest/usage/installation.html Installs plothist in editable mode with development and test dependencies using pip. Requires a virtual environment to be set up and activated. ```bash python3 -m pip install --editable ".[dev,test]" ``` -------------------------------- ### Updated Registry with New Properties Source: https://plothist.readthedocs.io/en/latest/_sources/basics/variable_registry.rst.txt Shows an example of the 'variable_registry.yaml' file after new properties have been added to variables using the 'update_variable_registry' function. ```yaml variable_0: name: variable_0 bins: auto range: - min - max label: variable_0 log: false legend_location: best legend_ncols: 1 docstring: '' text: default_text more_info: null new_property: false custom_list: - 1 - a - true custom_value: 0 variable_1: ... ``` -------------------------------- ### Install Development Version using pip Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Install plothist in editable mode with development and test dependencies using pip. This requires a pre-existing virtual environment. ```bash python3 -m pip install --editable ".[dev,test]" ``` -------------------------------- ### Create Font Directory on MacOS Source: https://plothist.readthedocs.io/en/latest/_sources/documentation/troubleshooting.rst.txt Use this command to create the Fonts directory in the user's Library on MacOS if it does not exist. This is a prerequisite for manual font installation. ```bash mkdir /Users/your_login_username/Library/Fonts # for MacOS ``` -------------------------------- ### Plot All Comparisons Between Data and Model Source: https://plothist.readthedocs.io/en/latest/_sources/advanced/model_examples.rst.txt This example demonstrates how to create a comprehensive comparison plot showing all available comparison types between data and a model. It utilizes both plot_data_model_comparison for the ratio and plot_comparison for additional metrics. ```python import plothist import numpy as np import boost_histogram as bh # Generate dummy data and model histograms data_hist = bh.Histogram(bh.axis.Regular(50, -3, 3)) data_hist.fill(np.random.normal(0, 1, 1000)) model_hist = bh.Histogram(bh.axis.Regular(50, -3, 3)) model_hist.fill(np.random.normal(0.5, 1.2, 1200)) # Plot with ratio comparison and add other comparisons fig, ax = plothist.plot_data_model_comparison( data_hist, model_hist, plot_kwargs={'label': 'Model'} ) plothist.plot_comparison( data_hist, model_hist, fig=fig, ax=ax, plot_kwargs={'label': 'Model'} ) # For a 1D histogram with regular binning, bin width can be obtained from hist.axes[0].widths[0] # Example: print(f"Bin width: {data_hist.axes[0].widths[0]}") ``` -------------------------------- ### Create and Use Variable Registry for Histograms Source: https://plothist.readthedocs.io/en/latest/_sources/basics/variable_registry.rst.txt This example demonstrates the complete workflow of creating, updating, and using the variable registry to plot histograms. It involves initializing the registry, setting binning and custom text, and then generating plots for each variable. ```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 Latin Modern Fonts on Linux Source: https://plothist.readthedocs.io/en/latest/documentation/troubleshooting.html Moves font files and extracts font archives to the specified directory for Linux systems. ```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 ``` -------------------------------- ### Unstacked Histograms Comparison Source: https://plothist.readthedocs.io/en/latest/_sources/advanced/model_examples.rst.txt Compares data to a model represented by unstacked histograms. This example uses the same data and model components as the stacked example but displays them unstacked. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_error_hist, plot_model, plot_comparison from plothist.utils import make_hist import numpy as np def make_data_and_model_hists(): # Data histogram data_hist = make_hist( np.random.normal(10, 2, 1000), bins=np.linspace(0, 20, 21), name="Data", label="Data", stat=True, stat_uncertainty_type="asymmetrical" ) # Model histograms model_hists = [ make_hist( np.random.normal(9, 2, 800), bins=np.linspace(0, 20, 21), name="Background", label="Background", stat=True, stat_uncertainty_type="asymmetrical" ), make_hist( np.random.normal(1, 1, 150), bins=np.linspace(0, 20, 21), name="Signal", label="Signal", stat=True, stat_uncertainty_type="asymmetrical" ), make_hist( np.random.normal(0.5, 0.5, 50), bins=np.linspace(0, 20, 21), name="Other", label="Other", stat=True, stat_uncertainty_type="asymmetrical" ), ] # Signal histogram (not part of the model) signal_hist = make_hist( np.random.normal(1.5, 0.5, 200), bins=np.linspace(0, 20, 21), name="Signal (standalone)", label="Signal (standalone)", stat=True, stat_uncertainty_type="asymmetrical" ) return data_hist, model_hists, signal_hist data_hist, model_hists, signal_hist = make_data_and_model_hists() plot_data_model_comparison( data_hist=data_hist, unstacked_components=model_hists, signal_hist=signal_hist, comparison_type="ratio", title="Unstacked histograms comparison" ) ``` -------------------------------- ### Install Latin Modern Fonts on Linux Source: https://plothist.readthedocs.io/en/latest/_sources/documentation/troubleshooting.rst.txt Commands to move the Latin Modern Math font and unzip the Roman and Sans variants into the ~/.fonts 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 ``` -------------------------------- ### Stacking Two 1D Histograms Source: https://plothist.readthedocs.io/en/latest/_downloads/adc0404bc2733c5cc8bc1b25b4168882/1d_elt1_stacked.ipynb Prepare two 1D histograms from dummy data and stack them using plot_hist. This example requires dummy data and matplotlib. ```python from plothist_utils import get_dummy_data df = get_dummy_data() import matplotlib.pyplot as plt from plothist import make_hist, plot_hist name = "variable_1" category = "category" x1 = df[name][df[category] == 1] x2 = df[name][df[category] == 2] x_range = (min(*x1, *x2), max(*x1, *x2)) h1 = make_hist(x1, bins=50, range=x_range) h2 = make_hist(x2, bins=50, range=x_range) ### fig, ax = plt.subplots() plot_hist( [h1, h2], label=["c1", "c2"], ax=ax, edgecolor="black", linewidth=0.5, histtype="stepfilled", stacked=True, ) ax.set_xlabel(name) ax.set_ylabel("Entries") ax.set_xlim(x_range) ax.legend() fig.savefig("1d_elt1_stacked.svg", bbox_inches="tight") ``` -------------------------------- ### Getting Comparison Values and Uncertainties Source: https://plothist.readthedocs.io/en/latest/_sources/basics/1d_hist.rst.txt Demonstrates how to retrieve the values, lower uncertainties, and upper uncertainties for a comparison between two histograms using `get_comparison()`. ```python from plothist import get_comparison values, lower_uncertainties, upper_uncertainties = get_comparison(h1, h2, comparison="ratio") ``` -------------------------------- ### Load Dummy Data Source: https://plothist.readthedocs.io/en/latest/basics/2d_hist.html Loads dummy data for plotting examples. This data can be used as a numpy ndarray or a pandas dataframe. ```python from plothist_utils import get_dummy_data df = get_dummy_data() ``` -------------------------------- ### Plotting 1D Histogram Asymmetry Comparison Source: https://plothist.readthedocs.io/en/latest/example_gallery/1d_hist/1d_comparison_asymmetry.html Generates dummy data, creates two 1D histograms, and plots their asymmetry comparison. Ensure `plothist_utils` and `plothist` are installed. ```python from plothist_utils import get_dummy_data df = get_dummy_data() name = "variable_1" x1 = df[name][df["category"] == 2] x2 = df[name][df["category"] == 3] x_range = (min(*x1, *x2), max(*x1, *x2)) from plothist import make_hist h1 = make_hist(x1, bins=50, range=x_range) h2 = make_hist(x2, bins=50, range=x_range) ### from plothist import plot_two_hist_comparison fig, ax_main, ax_comparison = plot_two_hist_comparison( h1, h2, xlabel=name, ylabel="Entries", h1_label=r"$\mathbfit{h}_1$", h2_label=r"$\mathbfit{h}_2$", comparison="asymmetry", # <-- ) fig.savefig("1d_comparison_asymmetry.svg", bbox_inches="tight") ``` -------------------------------- ### Plot Asymmetry Comparison Between Histograms and Functions Source: https://plothist.readthedocs.io/en/latest/advanced/other_advanced.html This example demonstrates plotting an asymmetry comparison between two histograms and their corresponding fit functions. It covers creating histograms, plotting them with error bars, overlaying fit functions, and visualizing the asymmetry in a separate subplot. Ensure necessary libraries like numpy and scipy.stats are imported. ```python import numpy as np from scipy.stats import norm from plothist import ( add_luminosity, add_text, create_comparison_figure, make_hist, plot_comparison, plot_error_hist, plot_function, ) # Define some random functions that will be used as Data fit functions def f1(x: np.ndarray) -> np.ndarray: return 4000 * norm.pdf(x, loc=-0.5, scale=1.6) def f2(x: np.ndarray) -> np.ndarray: return 4000 * norm.pdf(x, loc=0.5, scale=1.6) name = "variable_1" category = "category" x1 = df[name][df[category] == 5] x_range = (-9, 9) # Create the histograms used as data h1 = make_hist(x1 - 2.5, bins=50, range=x_range) h2 = make_hist(x1 - 1.5, bins=50, range=x_range) # Create the figure fig, (ax_main, ax_comparison) = create_comparison_figure( gridspec_kw={"height_ratios": [2, 1]} ) # Define the marker style marker_1 = { "color": "tab:red", "markeredgecolor": "tab:red", "ls": "None", "fmt": "o", "markersize": 5, "label": "$Data_1$", } marker_2 = { "color": "tab:blue", "markerfacecolor": "white", "markeredgecolor": "tab:blue", "ls": "None", "fmt": "o", "markersize": 5, "label": "$Data_2$", } # Plot the data plot_error_hist( h1, ax_main, uncertainty_type="symmetrical", density=False, **marker_1, ) plot_error_hist( h2, ax_main, uncertainty_type="symmetrical", density=False, **marker_2, ) # Plot the functions plot_function(f1, x_range, ax_main, color=marker_1["color"], label="Data$_1$ fit") plot_function( f2, x_range, ax_main, color=marker_2["color"], linestyle="--", label="Data$_2$ fit" ) # Plot the asymmetry comparison between the 2 histograms plot_comparison( h1, h2, ax=ax_comparison, h1_label=r"$Data_1$", h2_label=r"$Data_2$", comparison="asymmetry", comparison_ylim=(-1, 1), ) # Define the asymmetry of the 2 functions def asymmetry(x): return (f1(x) - f2(x)) / (f1(x) + f2(x)) # Plot the asymmetry of the 2 functions plot_function(asymmetry, x_range, ax_comparison, color="black") ax_main.legend() fig.align_ylabels() ax_main.set_xlim(x_range) ax_main.set_ylim(ymin=0) ax_main.set_ylabel("Entries") ax_main.legend() ax_comparison.set_xlim(x_range) ax_comparison.set_xlabel(name) add_text("Data and fit asymmetry comparison", ax=ax_comparison, x="right") add_luminosity( collaboration="LMN 3", ax=ax_main, lumi="(1 + 0.3)", preliminary=True, x="left" ) fig.savefig("asymmetry_comparison_advanced.svg", bbox_inches="tight") ``` -------------------------------- ### Install Latin Modern Fonts on MacOS Source: https://plothist.readthedocs.io/en/latest/_sources/documentation/troubleshooting.rst.txt Commands to move the Latin Modern Math font and unzip the Roman and Sans variants into the user's Library/Fonts directory on MacOS. ```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 ``` -------------------------------- ### Create and Compare 1D Histograms (Difference) Source: https://plothist.readthedocs.io/en/latest/_downloads/82d2ccf1e67b83b50945448fb3bd3f99/1d_comparison_difference.ipynb Generates two 1D histograms from dummy data and plots their difference. Ensure `plothist` and `plothist_utils` are installed. The `comparison='difference'` argument is key for this plot type. ```python from plothist_utils import get_dummy_data df = get_dummy_data() name = "variable_1" x1 = df[name][df["category"] == 2] x2 = df[name][df["category"] == 3] x_range = (min(*x1, *x2), max(*x1, *x2)) from plothist import make_hist h1 = make_hist(x1, bins=50, range=x_range) h2 = make_hist(x2, bins=50, range=x_range) ### from plothist import add_text, plot_two_hist_comparison fig, ax_main, ax_comparison = plot_two_hist_comparison( h1, h2, xlabel=name, ylabel="Entries", h1_label=r"$\mathcal{H}_{1}$", h2_label=r"$\mathcal{H}_{2}$", comparison="difference", # <-- ) add_text("Comparison of two hist with difference plot", ax=ax_main) add_text("Difference ax", x="right", ax=ax_comparison) fig.savefig("1d_comparison_difference.svg", bbox_inches="tight") ``` -------------------------------- ### Generate and Compare 1D Histograms using Pull Method Source: https://plothist.readthedocs.io/en/latest/_downloads/09b1b02446942a2f74cac85cfec38ec0/1d_comparison_pull.ipynb This snippet shows how to generate dummy data, create two 1D histograms, and then compare them using the pull method. The comparison highlights the difference between the two histograms relative to their statistical uncertainties. Ensure `plothist` and `plothist_utils` are installed. ```python from plothist_utils import get_dummy_data df = get_dummy_data() name = "variable_1" x1 = df[name][df["category"] == 2] x2 = df[name][df["category"] == 3] x_range = (min(*x1, *x2), max(*x1, *x2)) from plothist import make_hist h1 = make_hist(x1, bins=50, range=x_range) h2 = make_hist(x2, bins=50, range=x_range) ### from plothist import plot_two_hist_comparison fig, ax_main, ax_comparison = plot_two_hist_comparison( h1, h2, xlabel=name, ylabel="Entries", h1_label=r"$h_1$", h2_label=r"$h_2$", comparison="pull", # <--- ) fig.savefig("1d_comparison_pull.svg", bbox_inches="tight") ``` -------------------------------- ### Stacked and Unstacked Histograms Comparison Source: https://plothist.readthedocs.io/en/latest/_sources/advanced/model_examples.rst.txt Compares data to a model composed of both stacked and unstacked histograms. The total model is the sum of all components, regardless of their stacking. This example uses 2 stacked and 1 unstacked histogram for the model. ```python from plothist import plot_data_model_comparison from plothist.plotters import plot_error_hist, plot_model, plot_comparison from plothist.utils import make_hist import numpy as np def make_data_and_model_hists(): # Data histogram data_hist = make_hist( np.random.normal(10, 2, 1000), bins=np.linspace(0, 20, 21), name="Data", label="Data", stat=True, stat_uncertainty_type="asymmetrical" ) # Model histograms model_hists_stacked = [ make_hist( np.random.normal(9, 2, 800), bins=np.linspace(0, 20, 21), name="Background", label="Background", stat=True, stat_uncertainty_type="asymmetrical" ), make_hist( np.random.normal(1, 1, 150), bins=np.linspace(0, 20, 21), name="Signal", label="Signal", stat=True, stat_uncertainty_type="asymmetrical" ), ] model_hists_unstacked = [ make_hist( np.random.normal(0.5, 0.5, 50), bins=np.linspace(0, 20, 21), name="Other", label="Other", stat=True, stat_uncertainty_type="asymmetrical" ), ] # Signal histogram (not part of the model) signal_hist = make_hist( np.random.normal(1.5, 0.5, 200), bins=np.linspace(0, 20, 21), name="Signal (standalone)", label="Signal (standalone)", stat=True, stat_uncertainty_type="asymmetrical" ) return data_hist, model_hists_stacked, model_hists_unstacked, signal_hist data_hist, model_hists_stacked, model_hists_unstacked, signal_hist = make_data_and_model_hists() plot_data_model_comparison( data_hist=data_hist, stacked_components=model_hists_stacked, unstacked_components=model_hists_unstacked, signal_hist=signal_hist, comparison_type="ratio", title="Stacked and unstacked histograms comparison" ) ``` -------------------------------- ### Generate and Plot Data-Model Comparisons Source: https://plothist.readthedocs.io/en/latest/_downloads/9eed1779a6029de0d86c846714ed5553/model_all_comparisons_no_model_unc.ipynb This code generates dummy data, creates histograms for data and background components, and then plots various data-model comparisons. It's useful for visualizing how well a model predicts data when model uncertainty is not a factor. Ensure plothist and numpy are installed. ```python from plothist_utils import get_dummy_data df = get_dummy_data() from plothist import get_color_palette, make_hist # Define the histograms key = "variable_1" range = (-9, 12) category = "category" # Define masks 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] # Make histograms 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 ] # Optional: scale to data background_scaling_factor = data_hist.sum().value / sum(background_hists).sum().value background_hists = [background_scaling_factor * h for h in background_hists] ### import numpy as np from plothist import ( add_text, create_comparison_figure, plot_comparison, plot_data_model_comparison, set_fitting_ylabel_fontsize, ) fig, axes = create_comparison_figure( figsize=(6, 13), nrows=6, gridspec_kw={"height_ratios": [3, 1, 1, 1, 1, 1]}, hspace=0.3, ) background_sum = sum(background_hists) plot_data_model_comparison( data_hist=data_hist, stacked_components=background_hists, stacked_labels=background_categories_labels, stacked_colors=background_categories_colors, xlabel="", ylabel="Entries", model_uncertainty=False, # <-- comparison="ratio", fig=fig, ax_main=axes[0], ax_comparison=axes[1], ) add_text( r"Multiple data-model comparisons, $\mathbf{without}$ model uncertainty", ax=axes[0], ) add_text(r' $\mathbf{→}$ comparison = "ratio"', ax=axes[1], fontsize=13) for k_comp, comparison in enumerate( ["split_ratio", "pull", "relative_difference", "difference"], start=2 ): ax_comparison = axes[k_comp] # Copy the original histogram and set the uncertainties of the copy to 0. background_sum_copy = background_sum.copy() background_sum_copy[:] = np.c_[ background_sum_copy.values(), np.zeros_like(background_sum_copy.values()) ] plot_comparison( data_hist, background_sum_copy, ax=ax_comparison, comparison=comparison, xlabel="", h1_label="Data", h2_label="Pred.", h1_uncertainty_type="asymmetrical", ) if comparison == "pull": # Since the uncertainties of the model are neglected, the pull label is "(Data - Pred.)/sigma_Data" ax_comparison.set_ylabel(r"$\frac{Data-Pred.}{\sigma_{Data}}$") add_text( rf' $\mathbf{{→}}$ comparison = "{comparison}"', ax=ax_comparison, fontsize=13, ) set_fitting_ylabel_fontsize(ax_comparison) axes[-1].set_xlabel(key) fig.savefig("model_all_comparisons_no_model_unc.svg", bbox_inches="tight") ``` -------------------------------- ### Generate and Plot 'cubehelix' Color Palette Source: https://plothist.readthedocs.io/en/latest/_sources/example_gallery/utility/color_palette_squares.rst.txt Generates a color palette using the 'cubehelix' style and visualizes it using the `create_palette_plot` function. This example demonstrates using a different color scheme and does not add text labels to the plot. It's useful for visualizing the 'cubehelix' color progression. ```Python colors = get_color_palette("cubehelix", ncolors) figs.append(create_palette_plot(colors, fig_name="usage_cubehelix.svg")) ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Set up a Python virtual environment for isolating project dependencies. This is an optional but recommended step. ```bash python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Plotting a Simple 1D Histogram Source: https://plothist.readthedocs.io/en/latest/_downloads/22b8c072b1c6856b897ebb33f8263c04/1d_hist_simple.ipynb This snippet shows how to generate dummy data, create a 1D histogram using make_hist, and then plot it with plot_hist. It also sets axis labels and saves the figure to an SVG file. Ensure matplotlib and plothist are installed. ```python from plothist_utils import get_dummy_data df = get_dummy_data() ### import matplotlib.pyplot as plt from plothist import make_hist, plot_hist name = "variable_0" fig, ax = plt.subplots() h = make_hist(df[name]) plot_hist(h, ax=ax) ax.set_xlabel(name) ax.set_ylabel("Entries") fig.savefig("1d_hist_simple.svg", bbox_inches="tight") ``` -------------------------------- ### Prepare Data and Histograms Source: https://plothist.readthedocs.io/en/latest/_sources/example_gallery/model_ex/model_examples_stacked.rst.txt This snippet prepares dummy data and creates histograms for data, background components, and signal. It includes defining masks for different categories and scaling the background and signal histograms to match the data's total count. ```Python from plothist_utils import get_dummy_data df = get_dummy_data() from plothist import get_color_palette, make_hist # Define the histograms key = "variable_1" range = (-9, 12) category = "category" # Define masks 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] # Make histograms 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 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 ``` -------------------------------- ### Activate Development Environment (uv) Source: https://plothist.readthedocs.io/en/latest/usage/installation.html Activates the virtual environment created by `uv sync` for development. ```bash source .venv/bin/activate ``` -------------------------------- ### Create, Update, and Use Variable Registry Source: https://plothist.readthedocs.io/en/latest/basics/variable_registry.html Demonstrates the basic workflow of creating a variable registry, updating binning and custom information, and then using the registry to plot histograms with defined parameters. ```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") ``` -------------------------------- ### Update plothist to Latest Stable Version Source: https://plothist.readthedocs.io/en/latest/usage/installation.html Upgrades an existing plothist installation to the newest stable release from PyPI. Use `--user` if installed locally. ```bash python3 -m pip install --upgrade [--user] plothist ``` -------------------------------- ### Create and Plot Stacked Model Comparison Source: https://plothist.readthedocs.io/en/latest/_downloads/5962c3278a0a208584691a3aef9abf72/model_examples_stacked.ipynb Generates dummy data, creates histograms for data, stacked background components, and a separate signal. It then plots the data against the stacked model and overlays the signal. Includes luminosity information and saves the figure. ```python from plothist_utils import get_dummy_data df = get_dummy_data() from plothist import get_color_palette, make_hist # Define the histograms key = "variable_1" range = (-9, 12) category = "category" # Define masks 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] # Make histograms 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 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 ### from plothist import add_luminosity, plot_data_model_comparison, plot_hist fig, ax_main, ax_comparison = plot_data_model_comparison( data_hist=data_hist, stacked_components=background_hists, stacked_labels=background_categories_labels, stacked_colors=background_categories_colors, xlabel=key, ylabel="Entries", ) # Signal histogram not part of the model and therefore not included in the comparison plot_hist( signal_hist, ax=ax_main, color="red", label="Signal", histtype="step", ) ax_main.legend() add_luminosity( collaboration="plothist", ax=ax_main, lumi=3, lumi_unit="zb", preliminary=True ) fig.savefig("model_examples_stacked.svg", bbox_inches="tight") ``` -------------------------------- ### Create Font Directories Source: https://plothist.readthedocs.io/en/latest/documentation/troubleshooting.html Creates the necessary font directories for Linux and MacOS systems if they do not already exist. ```bash mkdir ~/.fonts # for Linux mkdir /Users/your_login_username/Library/Fonts # for MacOS ``` -------------------------------- ### Prepare Data and Make Histograms Source: https://plothist.readthedocs.io/en/latest/_downloads/a9b1e6deb3ca866265f9d20d7dd7367f/model_examples_pull_no_model_unc.ipynb This snippet prepares dummy data and creates histograms for data and background components. It defines masks for different categories and uses `make_hist` to generate histogram objects. The background histograms are optionally scaled to match the data's total sum. ```python from plothist_utils import get_dummy_data df = get_dummy_data() from plothist import get_color_palette, make_hist # Define the histograms key = "variable_1" range = (-9, 12) category = "category" # Define masks 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] # Make histograms 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 ] # Optional: scale to data background_scaling_factor = data_hist.sum().value / sum(background_hists).sum().value background_hists = [background_scaling_factor * h for h in background_hists] ``` -------------------------------- ### Update Plothist to Latest Stable Version Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Update an existing plothist installation to the newest stable release from PyPI. Use the --upgrade flag with the install command. ```bash python3 -m pip install --upgrade [--user] plothist ``` -------------------------------- ### List Nox Sessions Source: https://plothist.readthedocs.io/en/latest/CONTRIBUTING.html List all available nox sessions. Use this to see what tasks can be automated. ```bash nox -l ``` -------------------------------- ### Create and Plot a Model with Stacked and Unstacked Histograms Source: https://plothist.readthedocs.io/en/latest/_downloads/6c0a608ad869863ac711af8b3cc2d73b/model_with_stacked_and_unstacked_histograms_components.ipynb This snippet prepares dummy data, defines signal and background histograms, scales them, and then plots the model using stacked and unstacked components. It's useful for visualizing complex distributions where different components have varying contributions and uncertainties. ```python from plothist_utils import get_dummy_data df = get_dummy_data() from plothist import get_color_palette, make_hist # Define the histograms key = "variable_1" range = (-9, 12) category = "category" # Define masks 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] # Make histograms 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 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 ### from plothist import add_text, plot_model fig, ax = plot_model( stacked_components=background_hists, stacked_labels=background_categories_labels, stacked_colors=background_categories_colors, unstacked_components=[signal_hist], unstacked_labels=["Signal"], unstacked_colors=["black"], unstacked_kwargs_list=[{"linestyle": "dotted"}], xlabel=key, ylabel="Entries", model_sum_kwargs={"show": True, "label": "Model", "color": "navy"}, model_uncertainty_label="Stat. unc.", ) add_text("Model made of histograms", ax=ax) fig.savefig( "model_with_stacked_and_unstacked_histograms_components.svg", bbox_inches="tight", ) ``` -------------------------------- ### Clone Plothist Repository Source: https://plothist.readthedocs.io/en/latest/_sources/usage/installation.rst.txt Clone the plothist source code from GitHub to install the development version. Replace USERNAME with your GitHub username. ```bash git clone git@github.com:USERNAME/plothist.git cd plothist ``` -------------------------------- ### Generate and Compare Histograms Source: https://plothist.readthedocs.io/en/latest/_downloads/b4b7423eb051e2627505aeba087ea234/model_all_comparisons.ipynb Generates dummy data, creates data and background histograms, scales background to data, and plots multiple comparison types (ratio, pull, difference) between data and stacked background predictions. ```python from plothist_utils import get_dummy_data df = get_dummy_data() from plothist import get_color_palette, make_hist # Define the histograms key = "variable_1" range = (-9, 12) category = "category" # Define masks 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] # Make histograms 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 ] # Optional: scale to data background_scaling_factor = data_hist.sum().value / sum(background_hists).sum().value background_hists = [background_scaling_factor * h for h in background_hists] ### from plothist import ( add_text, create_comparison_figure, plot_comparison, plot_data_model_comparison, set_fitting_ylabel_fontsize, ) fig, axes = create_comparison_figure( figsize=(6, 13), nrows=6, gridspec_kw={"height_ratios": [3, 1, 1, 1, 1, 1]}, hspace=0.3, ) background_sum = sum(background_hists) plot_data_model_comparison( data_hist=data_hist, stacked_components=background_hists, stacked_labels=background_categories_labels, stacked_colors=background_categories_colors, xlabel="", ylabel="Entries", comparison="ratio", fig=fig, ax_main=axes[0], ax_comparison=axes[1], ) add_text( r"Multiple data-model comparisons, $\mathbf{with}$ model uncertainty", ax=axes[0], ) add_text(r' $\mathbf{\u2192}$ comparison = "ratio"', ax=axes[1], fontsize=13) for k_comp, comparison in enumerate( ["split_ratio", "pull", "relative_difference", "difference"], start=2 ): ax_comparison = axes[k_comp] plot_comparison( data_hist, background_sum, ax=ax_comparison, comparison=comparison, xlabel="", h1_label="Data", h2_label="Pred.", h1_uncertainty_type="asymmetrical", ) add_text( rf' $\mathbf{{{\u2192}}}$ comparison = "{comparison}"', ax=ax_comparison, fontsize=13, ) set_fitting_ylabel_fontsize(ax_comparison) axes[-1].set_xlabel(key) fig.savefig("model_all_comparisons.svg", bbox_inches="tight") ``` -------------------------------- ### Plotting Only the Comparison of 1D Histograms Source: https://plothist.readthedocs.io/en/latest/_sources/basics/1d_hist.rst.txt Example of using `plot_comparison()` to display only the comparison plot (e.g., efficiency) without the original histograms. ```python from plothist import Hist h1 = Hist.from_numpy( (np.random.normal(0, 1, 1000), np.linspace(-3, 3, 10)), name="h1" ) h2 = Hist.from_numpy( (np.random.normal(0.5, 1, 1000), np.linspace(-3, 3, 10)), name="h2" ) h1.plot_comparison(h2, comparison="efficiency", plot_kwargs={"only_comparison": True}) ``` -------------------------------- ### Create Variable Registry Source: https://plothist.readthedocs.io/en/latest/_sources/basics/variable_registry.rst.txt Initializes a variable registry by creating a 'variable_registry.yaml' file with default information for the specified variable keys. ```python from plothist import create_variable_registry variable_keys = ["variable_0", "variable_1", "variable_2"] create_variable_registry(variable_keys) ``` -------------------------------- ### Plot 1D Histogram with Uncertainties Source: https://plothist.readthedocs.io/en/latest/example_gallery/1d_hist/1d_elt2.html Creates a 1D histogram with error bars from data and plots it using matplotlib. Ensure plothist and matplotlib are installed. ```python import matplotlib.pyplot as plt from plothist import make_hist, plot_error_hist name = "variable_1" category = "category" x1 = df[name][df[category] == 3] h1 = make_hist(x1) fig, ax = plt.subplots() plot_error_hist(h1, ax=ax, color="black", label="$h1_{err}$") ax.set_xlabel(name) ax.set_ylabel("Entries") ax.set_ylim(ymin=0) ax.legend() fig.savefig("1d_elt2.svg", bbox_inches="tight") ``` -------------------------------- ### Simple 2D Histogram Plot Source: https://plothist.readthedocs.io/en/latest/_sources/basics/2d_hist.rst.txt Plots a basic 2D histogram using `make_2d_hist` and `plot_2d_hist`. Ensure `plothist` is installed and dummy data is loaded. ```python from plothist import make_2d_hist, plot_2d_hist hist = make_2d_hist(df, "x", "y") plot_2d_hist(hist) ``` -------------------------------- ### 2D Histogram Correlations with Variable Registry Source: https://plothist.readthedocs.io/en/latest/_sources/basics/2d_hist.rst.txt Plots correlations between multiple variables using the variable registry. This example requires the `plothist` library and dummy data. ```python from plothist import make_2d_hist, plot_2d_hist, VariableRegistry registry = VariableRegistry() registry.add_variable("x", "X", "", "", "") registry.add_variable("y", "Y", "", "", "") registry.add_variable("z", "Z", "", "", "") hist = make_2d_hist(df, "x", "y", weights=df["z"]) plot_2d_hist(hist, registry=registry, plot_correlations=True) ``` -------------------------------- ### Prepare and Plot 1D Histogram Ratio Comparison Source: https://plothist.readthedocs.io/en/latest/_downloads/46aad89fb4658158ac4437175ba92121/1d_comparison_ratio.ipynb This snippet shows how to load dummy data, create two 1D histograms from different categories, and then compare them using a ratio plot. It requires the `plothist` library and its utility functions. ```python from plothist_utils import get_dummy_data df = get_dummy_data() name = "variable_1" x1 = df[name][df["category"] == 2] x2 = df[name][df["category"] == 3] x_range = (min(*x1, *x2), max(*x1, *x2)) from plothist import make_hist h1 = make_hist(x1, bins=50, range=x_range) h2 = make_hist(x2, bins=50, range=x_range) ### from plothist import plot_two_hist_comparison # Default comparison is ratio fig, ax_main, ax_comparison = plot_two_hist_comparison( h1, h2, xlabel=name, ylabel="Entries", h1_label="h1", h2_label="h2", ) fig.savefig("1d_comparison_ratio.svg", bbox_inches="tight") ``` -------------------------------- ### Get Variable Information from Registry Source: https://plothist.readthedocs.io/en/latest/_sources/basics/variable_registry.rst.txt Retrieves the plotting information for a specific variable from the registry. The function returns a dictionary containing the variable's configuration. ```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': ''} ``` -------------------------------- ### Clear Matplotlib Font Cache Source: https://plothist.readthedocs.io/en/latest/_sources/documentation/troubleshooting.rst.txt Python code to find and remove matplotlib's font cache files. This is necessary after manually installing or updating 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]) ``` -------------------------------- ### List available nox sessions Source: https://plothist.readthedocs.io/en/latest/_sources/CONTRIBUTING.rst.txt Display a list of all available nox sessions that can be run individually. ```console nox -l ```