You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Reduce the bar width: Use a value that makes the total width per category less than 1. A solid choice is 0.3 (or 1/3 for exact spacing).
  2. 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 up 0.9 units 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 at index, the second at index+bar_width, third at index+2*bar_width—the center is exactly index+bar_width).

内容的提问来源于stack exchange,提问作者Jannik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:23:47