|
| 1 | +""" |
| 2 | +============= |
| 3 | +2D Histograms |
| 4 | +============= |
| 5 | +
|
| 6 | +Demonstrates how to plot 2-dimensional histograms. |
| 7 | +""" |
| 8 | + |
1 | 9 | import matplotlib.pyplot as plt
|
2 | 10 | import numpy as np
|
| 11 | +from matplotlib.colors import LogNorm |
| 12 | + |
| 13 | +############################################################################### |
| 14 | +# Plot a 2D histogram |
| 15 | +# ------------------- |
| 16 | +# |
| 17 | +# To plot a 2D histogram, one only needs two vectors of the same length, |
| 18 | +# corresponding to each axis of the histogram. |
3 | 19 |
|
4 | 20 | # Fixing random state for reproducibility
|
5 | 21 | np.random.seed(19680801)
|
6 | 22 |
|
| 23 | +# Generate a normal distribution, center at x=0 and y=5 |
| 24 | +x = np.random.randn(100000) |
| 25 | +y = .4 * x + np.random.randn(100000) + 5 |
| 26 | + |
| 27 | +fig, ax = plt.subplots() |
| 28 | +hist = ax.hist2d(x, y) |
| 29 | + |
| 30 | +############################################################################### |
| 31 | +# Customizing your histogram |
| 32 | +# -------------------------- |
| 33 | +# |
| 34 | +# Customizing a 2D histogram is similar to the 1D case, you can control |
| 35 | +# visual components such as the bin size or color normalization |
| 36 | + |
| 37 | +fig, axs = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True) |
| 38 | + |
| 39 | +# We can increase the number of bins on each axis |
| 40 | +axs[0].hist2d(x, y, bins=40) |
| 41 | + |
| 42 | +# As well as define normalization of the colors |
| 43 | +axs[1].hist2d(x, y, bins=40, norm=LogNorm()) |
7 | 44 |
|
8 |
| -x = np.random.randn(1000) |
9 |
| -y = np.random.randn(1000) + 5 |
| 45 | +# We can also define custom numbers of bins for each axis |
| 46 | +axs[2].hist2d(x, y, bins=(80, 10), norm=LogNorm()) |
10 | 47 |
|
11 |
| -# normal distribution center at x=0 and y=5 |
12 |
| -plt.hist2d(x, y, bins=40) |
13 | 48 | plt.show()
|
0 commit comments