|
| 1 | + |
| 2 | +""" |
| 3 | +Demo of how to produce multiple histograms side by side |
| 4 | +""" |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import matplotlib.pyplot as plt |
| 8 | + |
| 9 | +number_of_bins = 20 |
| 10 | + |
| 11 | +# An example of three data sets to compare |
| 12 | +number_of_data_points = 1000 |
| 13 | +labels = ["A", "B", "C"] |
| 14 | +data_sets = [np.random.normal(0, 1, number_of_data_points), |
| 15 | + np.random.normal(6, 1, number_of_data_points), |
| 16 | + np.random.normal(-3, 1, number_of_data_points)] |
| 17 | + |
| 18 | +# Computed quantities to aid plotting |
| 19 | +hist_range = (np.min(data_sets), np.max(data_sets)) |
| 20 | +binned_data_sets = [np.histogram(d, range=hist_range, bins=number_of_bins)[0] |
| 21 | + for d in data_sets] |
| 22 | +binned_maximums = np.max(binned_data_sets, axis=1) |
| 23 | +x_locations = np.arange(0, sum(binned_maximums), np.max(binned_maximums)) |
| 24 | + |
| 25 | +# The bin_edges are the same for all of the histograms |
| 26 | +bin_edges = np.linspace(hist_range[0], hist_range[1], number_of_bins+1) |
| 27 | +centers = .5 * (bin_edges + np.roll(bin_edges, 1))[:-1] |
| 28 | +heights = np.diff(bin_edges) |
| 29 | + |
| 30 | +# Cycle through and plot each histogram |
| 31 | +ax = plt.subplot(111) |
| 32 | +for x_loc, binned_data in zip(x_locations, binned_data_sets): |
| 33 | + lefts = x_loc - .5 * binned_data |
| 34 | + ax.barh(centers, binned_data, height=heights, left=lefts) |
| 35 | + |
| 36 | +ax.set_xticks(x_locations) |
| 37 | +ax.set_xticklabels(labels) |
| 38 | + |
| 39 | +ax.set_ylabel("Data values") |
| 40 | +ax.set_xlabel("Data sets") |
| 41 | + |
| 42 | +plt.show() |
| 43 | + |
0 commit comments