Black Lives Matter. Please consider donating to Black Girls Code today.

Histogram Bin Size with Plotly Express

Plotly Express Histogram is very cool because it gives us the possibility to easily set the facets, change the number of bins and nicely merges with Dash, but I would like to define the bin size.
I’ve seen this feature in go.Histogram() but not in px.Histogram
Has anyone found a workaround?

I’ve just figured out a workaround that worked:

            bin_width= 50
            # here you can choose your rounding method, I've chosen math.ceil
            nbins = math.ceil((df["data"].max() - df["data"].min()) / bin_width)
            fig = px.histogram(df, x="data", nbins=nbins)

Thanks for using the forum!

I think that what you are looking for is the fact that px.histogram() accepts an nbins parameter which allows you to set the size of the bins in your histogram.

For example:

import as px
df =
fig = px.histogram(df, x="total_bill", nbins=20)

This is documented at

I hope this answers your question!

Hi and thank you,
the question was related with the size of the bins instead of number of bins.
I was looking for a feature similar to xbins size in go.Histogram but in Plotly Express

    name='control', # name used in legend and hover labels
    xbins=dict( # bins used for histogram

Thanks for taking the time to further explain your use case.

You are right that you cannot pass an xbins attribute directly to the px.histogram constructor.

This is because Plotly Express was designed as a terse, high-level wrapper for the graph_objects library, so only a subset of the attributes that you can set using a graph_objects constructor are available in the Plotly Express constructors for figures.

However, it is important to note that the Plotly Express constructor always returns a graph_objects figure object.

This means you can use the update_traces method to set any attributes which are available on the figure after using the Plotly Express constructor.

import as px
df =
fig = px.histogram(df, x="total_bill")

fig.update_traces(xbins=dict( # bins used for histogram

I hope that answers your question.

1 Like

For future reference, I’d like to point out that start and end are optional attributes of the xbins_size parameter.

fig.update_traces(xbins_size=2) will also work, taking advantage of the magic underscore notation documented at

1 Like

@joseph.damiba, very helpful info, many thanks!