Matplotlib直方图X轴刻度错位:需设置刻度范围0.75-1.00
直方图X轴刻度错位修复方案
问题说明
生成直方图时出现X轴刻度与柱子错位的问题,需求为:X轴刻度从0.75起始、1.00结束,每个直方图柱宽度为0.05。当前输出的直方图中刻度无法与对应区间的柱子对齐。
修正后代码
import numpy as np import matplotlib.pyplot as plt # 假设已定义result、folder_numbers、var、idx变量 ranges = [(0.75, 0.8), (0.8, 0.85), (0.85, 0.9), (0.9, 0.95), (0.95, 1.00)] # 统计每个区间内的数值数量 count_values_in_ranges = [sum(1 for value in result if start <= value <= end) for start, end in ranges] # 打印区间统计结果 for i, (start, end) in enumerate(ranges): corresponding_folders = [ folder_numbers[j] for j, value in enumerate(result) if j < len(folder_numbers) and start <= value <= end] print(f"区间({start}-{end})内的数值数量(var={var}):{count_values_in_ranges[i]}") print(f"对应文件夹编号:{corresponding_folders}") # 设置画布参数 plt.figure(figsize=(10, 8), dpi=300) total_count = sum(count_values_in_ranges) bar_width = 0.05 colors = ['red', 'green', 'blue', 'orange', 'purple'] # 绘制柱子:以区间中心为x坐标,加上多组图偏移量 for i, (start, end) in enumerate(ranges): bar_center = (start + end) / 2 + idx * (bar_width * 6) # 6=5个柱子+1个间隔的总宽度 plt.bar(bar_center, count_values_in_ranges[i]/total_count*100, alpha=0.7, width=bar_width, label=f'区间({start}-{end})', color=colors[i]) # 设置X轴刻度:对齐区间边界,包含0.75到1.00的所有端点 tick_starts = np.array([start for start, end in ranges] + [1.00]) tick_positions = tick_starts + idx * (bar_width * 6) tick_labels = [f"{val:.2f}" for val in tick_starts] plt.xticks(tick_positions, tick_labels, rotation=0) plt.xlabel("数值区间") plt.ylabel("占比 (%)") plt.legend() plt.show()
关键修改点
- 柱子位置校准:用每个区间的中心值
(start+end)/2作为柱子的x坐标,确保柱子与数值区间精准对应,同时保留多组图的偏移逻辑idx*(bar_width*6)。 - 刻度位置修正:将刻度设置在区间的起始和结束端点(0.75、0.8、...、1.00),并同步加上多组图偏移量,保证刻度与区间边界对齐。
- 刻度标签完善:手动生成包含1.00的标签列表,避免
np.arange(0.75,1.00,0.05)遗漏终点的问题。
内容的提问来源于stack exchange,提问作者Dbatt
相关产品推荐
相关产品推荐

