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

如何在Matplotlib中调整直方图的Bin(区间)宽度?

How to Widen Histogram Bins in Your Python Code

Hey there! Let's tackle how to make those histogram bins wider—this is a quick fix once you know where to look.

Right now, your code creates bins that are 1 unit wide because you're generating x_axis_values with a step size of 1 (from -50 to 50 in increments of 1). To make each bin wider, you just need to increase that step size, which directly controls the width of each interval.

Step-by-Step Fix

  1. Adjust the bin interval size
    Change the step value in your range() (or np.arange()) call to a larger number. For example, if you want bins that are 5 units wide, set the step to 5:

    # Simplified way to generate wider bins (step = 5)
    x_axis_values = np.arange(-50, 51, 5)
    

    This creates bins like [-50, -45), [-45, -40), ..., [45, 50]—each with a width of 5.

  2. Sync your x-ticks with the new bins
    Don't forget to update your xticks to match the new bin boundaries, so your axis labels make sense:

    pl.xticks(np.arange(-50, 51, 5), rotation=45, fontsize=5)
    

Full Modified Code

Here's your updated code with 5-unit wide bins (feel free to adjust the step size to whatever width you need):

import numpy as np
import matplotlib.pyplot as plt as pl

# Assuming 'deltas' is your pre-defined data array
deltas = # Your existing data here

# Generate wider bins (step = 5 for 5ms width)
x_axis_values = np.arange(-50, 51, 5)

pl.xticks(np.arange(-50, 51, 5), rotation=45, fontsize=5)
pl.yticks(fontsize=10)
pl.hist(deltas, bins=x_axis_values, color='red', edgecolor='black', linewidth=0.5)
pl.title('Histogramm md_latency_is_bigger|0|main_latency_is_bigger')
pl.xlabel('deltas value, ms')
pl.ylabel('delta count, cnt')
pl.ticklabel_format(axis='y', style='plain')
pl.savefig('HISTOGRAMM.png')
pl.show()

Custom Bin Widths (If You Need More Control)

If you want non-uniform bin widths or specific intervals, you can manually define the bins array. For example, to make bins 10 units wide:

x_axis_values = [-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50]

Just make sure the array starts below your minimum data value and ends above your maximum data value.

That's it! The key takeaway is that the bins parameter defines the edges of each interval—wider gaps between edges mean wider bins.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:17:41