|
| 1 | +""" |
| 2 | +=========== |
| 3 | +Bihistogram |
| 4 | +=========== |
| 5 | +
|
| 6 | +How to plot a bihistogram with Matplotlib. |
| 7 | +""" |
| 8 | + |
| 9 | +import matplotlib.pyplot as plt |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +# Create a random number generator with a fixed seed for reproducibility |
| 13 | +rng = np.random.default_rng(19680801) |
| 14 | + |
| 15 | +# %% |
| 16 | +# Generate data and plot a bihistogram |
| 17 | +# ------------------------------------ |
| 18 | +# |
| 19 | +# To generate a bihistogram we need two datasets (each being a vector of numbers). |
| 20 | +# We will plot both histograms using plt.hist() and set the weights of the second |
| 21 | +# one to be negative. We'll generate data below and plot the bihistogram. |
| 22 | + |
| 23 | +N_points = 10_000 |
| 24 | + |
| 25 | +# Generate two normal distributions |
| 26 | +dataset1 = np.random.normal(0, 1, size=N_points) |
| 27 | +dataset2 = np.random.normal(1, 2, size=N_points) |
| 28 | + |
| 29 | +# Use a constant bin width to make the two histograms easier to compare visually |
| 30 | +bin_width = 0.25 |
| 31 | +bins = np.arange(np.min([dataset1, dataset2]), |
| 32 | + np.max([dataset1, dataset2]) + bin_width, bin_width) |
| 33 | + |
| 34 | +fig, ax = plt.subplots() |
| 35 | + |
| 36 | +# Plot the first histogram |
| 37 | +ax.hist(dataset1, bins=bins, label="Dataset 1") |
| 38 | + |
| 39 | +# Plot the second histogram |
| 40 | +# (notice the negative weights, which flip the histogram upside down) |
| 41 | +ax.hist(dataset2, weights=-np.ones_like(dataset2), bins=bins, label="Dataset 2") |
| 42 | +ax.axhline(0, color="k") |
| 43 | +ax.legend() |
| 44 | + |
| 45 | +plt.show() |
0 commit comments