如何缩小Matplotlib中两个柱状条之间的间距?
解决Matplotlib双柱状条间距过大的问题
我来帮你搞定这个问题~你遇到的核心问题是:当只有两个柱状条时,用np.arange(n)生成的x轴坐标是[0,1],两个柱子默认间隔1个单位,所以即使调小width,柱子之间的空隙还是会很大。下面给你两种实用的解决方案:
方法一:手动设置柱子的位置坐标
直接自定义x轴上柱子的位置,让它们的间隔更小,同时调整x轴刻度和显示范围来适配:
import numpy as np import matplotlib.pyplot as plt def evaluate_bar_graph(coherences, indices): assert len(coherences) == len(indices) n = len(coherences) # 自定义x位置,比如让两个柱子间隔0.3(默认是1) x = np.array([0, 0.3]) # 绘制柱状图,align='center'保证柱子居中在x位置上 plt.bar(x, coherences, width=0.1, align='center') # 将x轴刻度绑定到柱子的位置,显示对应的模型名称 plt.xticks(x, indices) plt.xlabel('Models') plt.ylabel('Coherence Value') # 调整x轴范围,去掉左右多余的空白 plt.xlim(-0.1, 0.4) plt.show()
方法二:调整x轴刻度的间距
如果你不想手动写x坐标,也可以通过修改np.arange的步长来缩小间隔,比如:
import numpy as np import matplotlib.pyplot as plt def evaluate_bar_graph(coherences, indices): assert len(coherences) == len(indices) n = len(coherences) # 生成间隔更小的x坐标,比如步长0.5 x = np.arange(0, n*0.5, 0.5) plt.bar(x, coherences, width=0.1, tick_label=indices, align='center') plt.xlabel('Models') plt.ylabel('Coherence Value') # 可选:调整x轴范围让布局更紧凑 plt.xlim(-0.2, x[-1]+0.2) plt.show()
关键原理
width参数只控制柱子本身的宽度,而柱子之间的间距由x轴上两个柱子的坐标差决定。默认np.arange(n)生成的坐标间隔是1,当n=2时就会导致间距过大,所以核心是缩小这个坐标间隔,再配合调整x轴范围让整体布局更美观。
内容的提问来源于stack exchange,提问作者user3778289
相关产品推荐
相关产品推荐

