{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Bihistogram\n\nHow to plot a bihistogram with Matplotlib.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\n# Create a random number generator with a fixed seed for reproducibility\nrng = np.random.default_rng(19680801)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Generate data and plot a bihistogram\n\nTo generate a bihistogram we need two datasets (each being a vector of numbers).\nWe will plot both histograms using plt.hist() and set the weights of the second\none to be negative. We'll generate data below and plot the bihistogram.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "N_points = 10_000\n\n# Generate two normal distributions\ndataset1 = np.random.normal(0, 1, size=N_points)\ndataset2 = np.random.normal(1, 2, size=N_points)\n\n# Use a constant bin width to make the two histograms easier to compare visually\nbin_width = 0.25\nbins = np.arange(np.min([dataset1, dataset2]),\n                    np.max([dataset1, dataset2]) + bin_width, bin_width)\n\nfig, ax = plt.subplots()\n\n# Plot the first histogram\nax.hist(dataset1, bins=bins, label=\"Dataset 1\")\n\n# Plot the second histogram\n# (notice the negative weights, which flip the histogram upside down)\nax.hist(dataset2, weights=-np.ones_like(dataset2), bins=bins, label=\"Dataset 2\")\nax.axhline(0, color=\"k\")\nax.legend()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. tags:: plot-type: histogram, domain: statistics, purpose: showcase\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}