3

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.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Adrien
  • 433
  • 1
  • 3
  • 13
  • @Adrien How did my suggestion work out for you? – vestland Jul 07 '20 at 21:37
  • @vestland thank you for your quick answer. Your suggestion does work but if you use go.bar you can not use the plotly histogram methods. I think you have to chose either between customizing the binning of your data or using all the features and methods of plotly histograms. – Adrien Jul 15 '20 at 09:39

1 Answers1

4

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()
vestland
  • 55,229
  • 37
  • 187
  • 305