Python 脚本。在绘制直方图时,面临 x 轴刻度的问题

问题描述 投票:0回答:1

“我生成了一个直方图,图形看起来不错,除了 x 轴刻度线未位于条形图的中间,有时刻度线会随机放置在条形图的边缘或中心。

直方图 - 屏幕截图

在屏幕截图中,条形下方的刻度是随机放置的,但我需要刻度位置应恰好放置在条形下方的中间位置,如 191。”

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, '{filename?_{timestamp}.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, botton=0, label=key)
            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_valve}')
            plt.ylabel('Count')
            if key:
                t1 = key.replace("in_ps", ""), replace(" in_m", "")
            plt.title(t1)


            # Calculate tick positions for the y-axis
            max_count = int (max(n))
            # Set y-axis ticks to include 0 and the maximum count
            y_ticks = [0, max_count]
            plt.yticks(y_ticks)

            # Ensure unique x-axis tick values
            unique_values = np.unique(values)
            plt.xticks(unique_values, rotation=45)   #To rotate values on x-axis ticks use thisline

            # Annotate each bar with its count
            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()/1,
                  str(int(n[i])), ha='center', color='black') # Centering count on top of the bar

            plt.tight_layout()
            pdt.savefig()
            plt.close()

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

generate_histogram(data_dict)
python-3.x pandas numpy matplotlib data-science
1个回答
0
投票

也许尝试手动计算

xticks
值,使其与您的直方图
bins
匹配。您需要计算每个箱的中心并将其放置在图表上,如下所示:

bin_centers = 0.5 * (bins[:-1] + bins[1:])
plt.xticks(bin_centers, np.round(bin_centers, 0))
© www.soinside.com 2019 - 2024. All rights reserved.