Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 629baa8

Browse filesBrowse files
Merge pull request #27182 from i-jey/bihistogram_example
Add example for plotting a bihistogram
2 parents b34e704 + 72d6042 commit 629baa8
Copy full SHA for 629baa8

File tree

Expand file treeCollapse file tree

1 file changed

+45
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+45
-0
lines changed
+45Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.