Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 92a8f88

Browse files
committed
Example for plotting a bihistogram
1 parent e501543 commit 92a8f88

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 one to be negative.
21+
# We'll generate data below and plot the bihistogram.
22+
23+
N_points = 10_000
24+
n_bins = 30
25+
26+
# Generate two normal distributions
27+
dataset1 = np.random.normal(0, 1, size=N_points)
28+
dataset2 = np.random.normal(1, 2, size=N_points)
29+
30+
fig, ax = plt.subplots()
31+
32+
# Plot the first histogram
33+
ax.hist(dataset1, bins=n_bins, label="Dataset 1")
34+
35+
# Plot the second histogram (notice the negative weights, which flip the histogram upside down)
36+
ax.hist(dataset2, weights=-np.ones_like(dataset2), bins=n_bins, label="Dataset 2")
37+
ax.axhline(0, color="k")
38+
ax.legend()
39+
40+
plt.show()

0 commit comments

Comments
 (0)