pythonplotly

How to add space between bars using Plotly?


import plotly.express as px

df = px.data.tips()
fig = px.histogram(
    pd.DataFrame({'price': prices}), 
    x="price",
    )
fig.show()

enter image description here

Is there a way to separate the different bins?


Solution

  • You can use 'update_layout(bargap=<gap_value>' before show it!

    And for a better visualization, you can group bars by a range, like 10 to 20.

    
    import plotly.express as px
    import numpy as np
    
    np.random.seed(42)
    count = np.random.randint(1, 10, 100)
    price = np.random.uniform(10, 100, 100)
    
    fig = px.histogram(x=price, y=count, nbins=20,
                       labels={'x': 'Price', 'y': 'Count'},
                       title="Histogram of Count vs Price",
                       barmode="group",
                       barnorm=None
                       )
    
    # Insert the gap!
    fig.update_layout(bargap=0.2)
    
    fig.show()
    

    My code results:

    Graph Result of Code Above

    You can find more information on Plotly documentation:

    https://plotly.com/python/reference/layout/#layout-bargap