Last active
August 1, 2022 15:00
-
-
Save spestana/606d3c9f02b7c6e6756bd0fe94995bbc to your computer and use it in GitHub Desktop.
Stacked bar chart for two data sets, normalized by the number of points within each bin, with numpy and matplotlib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def stacked(adata, bdata, x_min, x_max, bin_width, title, xlabel): | |
# by Cassie Lumbrazo, 7/29/2022 | |
np.seterr(invalid='ignore') #ignore the runtime errors for 0/0 | |
# define datasets | |
a = adata.copy(deep=True) | |
b = bdata.copy(deep=True) | |
# note that these give you bin edges, not bin centers | |
a_count, a_bin_edges = np.histogram(a, bins=range(int(x_min), int(x_max), int(bin_width))) | |
b_count, b_bin_edges = np.histogram(b, bins=range(int(x_min), int(x_max), int(bin_width))) | |
# to get bin centers, add 1/2 of the bin width (in this case 1/2 of 1 is 0.5) to the bin edges | |
# (but drop the last bin edge value) | |
half_range = bin_width / 2 | |
a_bin_centers = a_bin_edges[:-1] + half_range # SINCE SW IN 100 w/m2 BINS | |
b_bin_centers = b_bin_edges[:-1] + half_range | |
# calculate percent based on total (a and b) in each bin | |
a_percent = a_count / (a_count + b_count) | |
b_percent = b_count / (a_count + b_count) | |
# remove nans where there was missing a or b data | |
a_percent[np.isnan(a_percent)] = 0 | |
b_percent[np.isnan(b_percent)] = 0 | |
# make the stacked bar plot | |
fig, ax = plt.subplots() | |
ax.bar(a_bin_edges[1:], a_percent, width=bin_width, label=namesnow, color=colorsnow, alpha=.7) | |
ax.bar(a_bin_edges[1:], b_percent, width=bin_width, bottom=a_percent, label=namesnowunload, color=colorsnowunload, alpha=.7) | |
plt.xlim(x_min, x_max) | |
plt.title(title) | |
plt.xlabel(xlabel) | |
plt.grid() | |
plt.legend() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment