Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: How to customize different bin widths for a plotly histogram?

I am trying to display an histogram with bins that have a different/customizable width. It seems that Plotly only allows to have a uniform bin width with xbins = dict(start , end, size).

For example, I would like for a set of data with integers between 1 and 10 display an histogram with bins representing the share of elements in [1,5[, in [5,7[ and [7,11[. With Matplotlib you can do it with an array representing the intervalls of the bins, but with plotly it seems thaht i must chose a uniform width.

By the way, I am not using Matplotlib since Plotly allows me to use features Matplotlib doesn't have.

like image 863
Adrien Avatar asked Oct 25 '25 02:10

Adrien


1 Answers

If you're willing to handle the binning outside plotly, you can set the widths in a go.bar object using go.Bar(width=<widths>) to get this:

enter image description here

Complete code

import numpy as np
import plotly.express as px
import plotly.graph_objects as go

# sample data
df = px.data.tips()

# create bins
bins1 = [0, 15, 50]
counts, bins2 = np.histogram(df.total_bill, bins=bins1)
bins2 = 0.5 * (bins1[:-1] + bins2[1:])

# specify sensible widths
widths = []
for i, b1 in enumerate(bins1[1:]):
    widths.append(b1-bins2[i])

# plotly figure
fig = go.Figure(go.Bar(
    x=bins2,
    y=counts,
    width=widths # customize width here
))

fig.show()
like image 190
vestland Avatar answered Oct 26 '25 16:10

vestland