Matplotlib多组数据刻度不一致问题:第二组图表被第一组挤压变形
解决Matplotlib柱状图因数据量级差异导致小数值柱子不可见的问题
你的问题核心是两组数据量级差距过大(CA组数值达百万/千万级,ME组仅百/千级),导致小数值的柱子被压缩得几乎无法辨认。下面提供几个实用的解决办法:
方案1:使用双Y轴
给不同量级的数据分配左右两个Y轴,分别适配各自的数值范围,既能保留整体对比,又能清晰展示小数值柱子:
import numpy as np import matplotlib.pyplot as plt labels = ['CA', 'ME'] Admitted = [500000, 100] Applied = [10000000, 1000] x = np.arange(len(labels)) width = 0.35 fig, ax1 = plt.subplots() # 左Y轴适配大数值(CA组) rects1 = ax1.bar(x - width/2, Admitted, width, label='Admitted', color='tab:blue') rects2 = ax1.bar(x + width/2, Applied, width, label='Applied', color='tab:orange') ax1.set_xticks(x, labels) ax1.set_ylabel('大数值范围') ax1.legend(loc='upper left') # 右Y轴适配小数值(ME组) ax2 = ax1.twinx() ax2.set_ylim(0, max(Admitted[1], Applied[1]) * 1.2) ax2.set_ylabel('小数值范围') # 给所有柱子添加数值标签 ax1.bar_label(rects1, padding=3) ax1.bar_label(rects2, padding=3) fig.tight_layout() plt.show()
方案2:使用对数坐标轴
将Y轴改为对数刻度,让不同量级的数据在同一轴上均衡展示,避免小数值被压缩:
import numpy as np import matplotlib.pyplot as plt labels = ['CA', 'ME'] Admitted = [500000, 100] Applied = [10000000, 1000] x = np.arange(len(labels)) width = 0.35 fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, Admitted, width, label='Admitted') rects2 = ax.bar(x + width/2, Applied, width, label='Applied') ax.set_xticks(x, labels) ax.legend() ax.bar_label(rects1, padding=3) ax.bar_label(rects2, padding=3) # 设置对数刻度,手动指定刻度点让显示更清晰 ax.set_yscale('log') ax.set_yticks([100, 1000, 10000, 100000, 1000000, 10000000]) ax.get_yaxis().set_major_formatter(plt.ScalarFormatter()) fig.tight_layout() plt.show()
方案3:拆分成分组子图
将CA和ME的数据拆分为两个独立子图,各自适配自身的数值范围,完全避免挤压问题:
import numpy as np import matplotlib.pyplot as plt labels = ['Admitted', 'Applied'] ca_data = [500000, 10000000] me_data = [100, 1000] x = np.arange(len(labels)) width = 0.35 # 创建1行2列的子图 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5)) # 绘制CA组数据 rects_ca = ax1.bar(x, ca_data, width, label='CA') ax1.set_xticks(x, labels) ax1.set_title('CA 申请/录取数据') ax1.bar_label(rects_ca, padding=3) # 绘制ME组数据 rects_me = ax2.bar(x, me_data, width, label='ME', color='tab:orange') ax2.set_xticks(x, labels) ax2.set_title('ME 申请/录取数据') ax2.bar_label(rects_me, padding=3) fig.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者A.E
相关产品推荐
相关产品推荐

