使用numpy histogram_bin_edges仍无法让直方图区间边缘与图表刻度对齐
问题:直方图区间边缘无法与X轴刻度对齐
我希望直方图的区间边缘能与图表的xticks对齐。查阅相关回答后,我尝试了计算并传入bins的方法,但仍无法实现对齐:
我重点尝试了以下操作但无效果:将my_bins转为列表(tolist()),甚至强制设置xticks匹配my_bins,依然无法对齐。相关代码片段:
my_bins = np.histogram_bin_edges(a=dataframe[data_cols].values.ravel(), bins='sqrt').tolist() axes_dict['histogram'].set_xticks(ticks=my_bins) axes_dict['histogram'].set_xticklabels(labels=my_bins)
请问接下来我该尝试什么方法?以下是完整示例代码:
from matplotlib.figure import Figure from PIL import Image import pandas as pd import numpy as np my_fig = Figure(**{'layout': 'constrained'}) mosaic = {'mosaic': [['histogram']], 'gridspec_kw': {'wspace': 0.0, 'hspace': 0.0}} axes_dict = my_fig.subplot_mosaic(**mosaic) columns = ['label', 'obs1'] data = [('', 74.03), ('', 73.995), ('', 73.988), ('', 74.002), ('', 73.992), ('', 74.009), ('', 73.995), ('', 73.985), ('', 74.008), ('', 73.998), ('', 73.994), ('', 74.004), ('', 73.983), ('', 74.006), ('', 74.012), ('', 74.0), ('', 73.994), ('', 74.006), ('', 73.984), ('', 74.0), ('', 73.988), ('', 74.004), ('', 74.01), ('', 74.015), ('', 73.982)] dataframe = pd.DataFrame(data, columns=columns) data_cols = ['obs1'] my_bins = np.histogram_bin_edges(a=dataframe[data_cols].values.ravel(), bins='sqrt').tolist() # my_bins = [73.982, 73.9916, 74.0012, 74.0108, 74.0204, 74.03] axes_dict['histogram'].hist(**{'x': [74.03, 73.995, 73.988, 74.002, 73.992, 74.009, 73.995, 73.985, 74.008, 73.998, 73.994, 74.004, 73.983, 74.006, 74.012, 74.0, 73.994, 74.006, 73.984, 74.0, 73.988, 74.004, 74.01, 74.015, 73.982], 'bins': [73.982, 73.9916, 74.0012, 74.0108, 74.0204, 74.03], 'label': '', 'color': 'C0', 'zorder': 3.0, 'alpha': 0.5, 'histtype': 'step', 'align': 'left', 'orientation': 'vertical'}) axes_dict['histogram'].set_xticks(ticks=my_bins) axes_dict['histogram'].set_xticklabels(labels=my_bins) my_fig.savefig('example_figure_for_stackoverflow.png') Image.open('example_figure_for_stackoverflow.png').show()
解决方案
问题核心在于你设置的align='left'参数——当使用histtype='step'时,这个参数会让直方图的步线左对齐到bin的起始位置,但matplotlib自动调整的x轴范围会导致刻度和区间边缘错位。只需要做两个关键调整:
- 移除或修改
align参数:对于histtype='step',如果要让区间边缘和刻度完全对齐,直接删掉align='left'(默认值mid会适配步线的显示逻辑),或者设置为align='edge'; - 强制x轴范围匹配bins首尾值:避免matplotlib自动扩展x轴范围,确保刻度和区间边缘完全重合。
修改后的关键代码片段:
# 绘制直方图时调整参数 axes_dict['histogram'].hist(**{'x': dataframe[data_cols].values.ravel(), 'bins': my_bins, 'label': '', 'color': 'C0', 'zorder': 3.0, 'alpha': 0.5, 'histtype': 'step', 'orientation': 'vertical'}) # 强制x轴范围与bins一致 axes_dict['histogram'].set_xlim(my_bins[0], my_bins[-1]) # 设置刻度(无需额外转列表,直接用my_bins即可) axes_dict['histogram'].set_xticks(ticks=my_bins) # 可选:格式化刻度标签,避免过多小数位 axes_dict['histogram'].set_xticklabels([f'{x:.4f}' for x in my_bins])
这样调整后,直方图的区间边缘就会和x轴刻度完全对齐了。
内容的提问来源于stack exchange,提问作者Python_Learner
相关产品推荐
相关产品推荐

