Python matplotlib分组柱状图重叠问题求助
Fixing Overlapping Grouped Bar Charts in Matplotlib
Hey there! Let's sort out why your grouped bars are overlapping—it's a common tiny logic tweak, no worries.
The Root Cause
Your bar_width is too large for three bars per category. You set bar_width = 0.45, so three bars take up a total width of 3 * 0.45 = 1.35. But since each category (from np.arange(n_groups)) is spaced 1 unit apart, this means the third bar of one category spills into the next category's space, causing the overlap.
The Fix
- Reduce the bar width: Use a value that makes the total width per category less than 1. A solid choice is
0.3(or1/3for exact spacing). - Adjust x-tick positions: Center the ticks under the middle of each three-bar group instead of the original position.
Here's your modified code with these changes highlighted:
import numpy as np import matplotlib.pyplot as plt # Assuming market, dmarket, pmarket are defined elsewhere with 3 elements each n_groups = 3 credits = (market[0], market[1], market[2]) debits = (dmarket[0], dmarket[1], dmarket[2]) profits = (pmarket[0], pmarket[1], pmarket[2]) fig, ax = plt.subplots() index = np.arange(n_groups) # Reduced bar width to fit three bars per category bar_width = 0.3 opacity = 0.4 error_config = {'ecolor': '0.3'} rectsCredits = plt.bar(index, credits, bar_width, alpha=opacity, color='b', error_kw=error_config, label='Credit') rectsDebits = plt.bar(index + bar_width, debits, bar_width, alpha=opacity, color='r', error_kw=error_config, label='Debit') rectsProfits = plt.bar(index + 2*bar_width, profits, bar_width, alpha=opacity, color='g', error_kw=error_config, label='Profits') # Adjusted tick position to center under the three-bar group plt.xticks(index + bar_width, ('Tariff Market', 'Wholesale Market', 'Balancing Market')) plt.legend() plt.tight_layout() def autolabel(rects): """ Attach a text label above each bar displaying its height """ for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.01 * height, '%d' % int(height), ha='center', va='bottom') autolabel(rectsCredits) autolabel(rectsDebits) autolabel(rectsProfits) plt.show()
Why This Works
- With
bar_width = 0.3, three bars take up0.9units of space per category, leaving a small gap between groups for clarity. - The
plt.xticks(index + bar_width, ...)moves each tick to the middle of the three bars (since the first bar starts atindex, the second atindex+bar_width, third atindex+2*bar_width—the center is exactlyindex+bar_width).
内容的提问来源于stack exchange,提问作者Jannik
相关产品推荐
相关产品推荐

