Reputation: 1368
I am drawing a couple of stacked histograms using the code below. I am using the same bin edges for both so they are aligned nicely.
How can I have these displayed on the same chart? I.e. a green/red and a blue/orange bar per each bin -- side-by-side.
I saw many questions and answers similar to this suggesting using a bar chart and calculating the width of the bars, but this seems like something that should be supported out-of-the-box, at least in matplotlib.
Also, can I draw stacked histograms directly with seaborn? I wasn't able to find a way.
plt.hist( [correct_a, incorrect_a], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)
plt.hist( [correct_b, incorrect_b], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)
Upvotes: 3
Views: 1656
Reputation: 2119
Well, I think plt.bar
is your best bet here. To create stacked histograms, you can use its bottom
argument. To display two bar charts side-by-side you can shift the x
values by some width
, just like in this original matplotlib example:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(16, 8))
correct_a = np.random.randint(0, 20, 20)
incorrect_a = np.random.randint(0, 20, 20)
correct_b = np.random.randint(0, 20, 20)
incorrect_b = np.random.randint(0, 20, 20)
edges = len(correct_a)
width=0.35
rects1 = ax.bar(np.arange(edges), incorrect_a, width, color="red", label="incorrect_a")
rects2 = ax.bar(np.arange(edges), correct_a, width, bottom=incorrect_a, color='seagreen', label="correct_a")
rects3 = ax.bar(np.arange(edges) + width, incorrect_b, width, color="blue", label="incorrect_b")
rects4 = ax.bar(np.arange(edges) + width, correct_b, width, bottom=incorrect_b, color='orange', label="correct_b")
# placing the ticks to the middle
ticks_aligned = np.arange(edges) + width // 2
ax.set_xticks(np.arange(edges) + width / 2)
ax.set_xticklabels((str(tick) for tick in ticks_aligned))
ax.legend()
This returns:
Upvotes: 2
Reputation: 1527
Here is a simple example (histograms are not stacked) for 2 histograms displayed together with each bin having a dedicated place for each of them side by side:
# generating some data for this example:
a = [1,2,3,4,3,4,2,3,4,5,4,3,4,5,4,1,2,3,2,1,3,4,5,6,7,6,5,4,3,4,6,5,4,3,4]
b = [1,2,3,4,5,6,7,6,5,6,7,6,5,4,3,4,5,6,7,6,7,6,7,5,4,3,2,1,3,4,5,6,5,6,5,6,7,6,7]
# plotting 2 histograms with bars centered differently within each bin:
plt.hist(a, bins=5, align='left', rwidth=0.5)
plt.hist(b, bins=5, align='mid', rwidth=0.5, color='r')
Upvotes: 0