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

绘制直方图时X轴刻度未居中于柱体的技术问题求助

直方图X轴刻度精准对齐解决方案

问题

生成的直方图X轴刻度未对准柱体正下方中心,位置随机(有时在边缘有时在中心),需要让刻度精准落在每个柱体的正下方中间位置。

问题根源

原代码中用np.unique(values)作为X轴刻度位置,这是把刻度绑定到原始数据的唯一值上,和直方图柱体的实际位置不匹配。直方图的柱体位置由bins数组定义,每个柱体的中心是相邻两个bin的平均值。

修正后的完整代码

import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

def generate_histogram(data_dict):
    result_folder = 'graphs'
    if not os.path.exists(result_folder):
        os.makedirs(result_folder)
    # 修正文件名语法错误
    pdf_file = os.path.join(result_folder, f'histogram_{np.datetime64("now")}.pdf')
   
    with PdfPages(pdf_file) as pdf:
        for key, values in data_dict.items():
            plt.figure(figsize=(25, 20))
            # 修正参数拼写与引号错误
            n, bins, patches = plt.hist(values, bins=38, edgecolor="black", alpha=0.7, rwidth=0.8, bottom=0, label=key)
            
            key_value = ""
            if key.endswith("Width_in_ps"):
                key_value = "Width in ps"
            if key.endswith("Height_in_mV"):
                key_value = "Height in mv"
            plt.xlabel(f'{key_value}')
            plt.ylabel('Count')
            
            # 修正字符串替换语法错误
            if key:
                t1 = key.replace("in_ps", "").replace("_in_m", "")
            plt.title(t1)

            # Y轴刻度设置保持不变
            max_count = int(max(n))
            y_ticks = [0, max_count]
            plt.yticks(y_ticks)

            # 计算每个柱体的中心位置作为X轴刻度坐标
            tick_positions = (bins[:-1] + bins[1:]) / 2
            # 可根据需求替换标签为原始数据唯一值,需保证数量与tick_positions一致
            plt.xticks(tick_positions, [f'{pos:.1f}' for pos in tick_positions], rotation=45)

            # 修正柱状图顶部标注的语法错误
            for i in range(len(patches)):
                if n[i] != 0:
                    plt.text(patches[i].get_x() + patches[i].get_width() / 2, patches[i].get_height(),
                             str(int(n[i])), ha='center', color='black')

            plt.tight_layout()
            # 修正拼写错误
            pdf.savefig()
            plt.close()

    print(f"\033[92mPDF file '{pdf_file}' has been generated. \033[0m")

# 调用示例(需传入正确的data_dict)
# generate_histogram(data_dict)

关键修改点

  • 刻度位置计算:通过(bins[:-1] + bins[1:]) / 2精准计算每个柱体的中心坐标,作为X轴刻度的定位点
  • 语法错误修正:修复了原代码中字符串引号不匹配、变量名拼写错误(如botton→bottom、pdt→pdf)、方法调用语法错误(如items)→items())
  • 标签灵活调整:如果需要显示原始数据的唯一值作为刻度标签,可将plt.xticks的标签参数替换为unique_values,需确保两者数量一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:20:11