Black Lives Matter. Please consider donating to Black Girls Code today.
Dash Enterprise delivers an incredible 21x cost savings 💸Download the e-book!

Plotly Histogram nbinx does not provide the right number of bins in Python

With the following code I get 15 bins instead of 20 as expected.

import pandas as pd
from plotly.offline import plot
from plotly.graph_objs import Histogram

df = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/tmp.txt')

plot(dict(data=[Histogram(x=df.ws, nbinsx=20)],
          layout=dict(xaxis=dict(dtick=1), bargap=0.25)
         ))

I also noticed this. Did you manage to find a solution?

Setting nbinx specifies the maximum number of desired bins not the exact number of bins to show. WIth nbinx set, plotly still attempts to round the number of bins to nice numbers. See the full attribute reference here for more info.

To set the exact number of bins, you’ll need to use a combination of xbins.start, xbins.end and xbins.size.

I tried to set the xbins.start, end, size, but no working. Do you have an example?

This finally worked for me:

fig = go.Figure()
fig.add_trace(go.Histogram(x=penetration.p_member, name=‘population’, histnorm=‘percent’,
xbins=dict(start=‘0’,end=‘0.4’, size=0.05)
),

         )

fig.add_trace(go.Histogram(x=df_test88.toPandas().p_member, name=‘sample_88’, histnorm=‘percent’,
xbins=dict(start=‘0’,end=‘0.4’, size=0.05)
))
fig.update_layout(barmode=‘overlay’)

Reduce opacity to see both histograms

fig.update_traces(opacity=0.75)
fig.show()