Histogram Bin Size with Plotly Express

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 plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")

fig.update_traces(xbins=dict( # bins used for histogram
        start=0.0,
        end=60.0,
        size=2
    ))

fig.show()

I hope that answers your question.

7 Likes