Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control distance between bars in bar chart

I have two peaces of code that produce sameme result, so any could be used for answer.

First:

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(
    name='Group 1',
    x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4],
    error_y=dict(type='data', array=[1, 0.5, 1.5]),
    width=0.15
))
fig.add_trace(go.Bar(
    name='Group 2',
    x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3],
    error_y=dict(type='data', array=[0.5, 1, 2]),
    width=0.15
))
fig.update_layout(barmode='group')
fig.show()

Second:

import plotly.graph_objects as go

fig = go.Figure(data=[
    go.Bar(
            name='Group 1',
            x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4],
            error_y=dict(type='data', array=[1, 0.5, 1.5]),
            width=0.15),
    go.Bar(
            name='Group 2',
            x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3],
            error_y=dict(type='data', array=[0.5, 1, 2]),
            width=0.15)
])
# Change the bar mode
fig.update_layout(barmode='group')
fig.show()

They both look like: enter image description here



Question: How can I control the distance between bars of different groups and bars of different Vars?

like image 500
vasili111 Avatar asked Dec 29 '25 22:12

vasili111


1 Answers

There are 2 properties that you are asking for. They are as follows:

  1. bargap - gap between bars of adjacent location coordinates.
  2. bargroupgap - gap between bars of the same location coordinate.

But there is a catch here, if you set width then both the properties are ignored. So, remove the width value from the code and setting the above properties should work.

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(
    name='Group 1',
    x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4],
    error_y=dict(type='data', array=[1, 0.5, 1.5])
))
fig.add_trace(go.Bar(
    name='Group 2',
    x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3],
    error_y=dict(type='data', array=[0.5, 1, 2])
))
fig.update_layout(barmode='group', bargap=0.30,bargroupgap=0.0)
fig.show()
like image 55
bigbounty Avatar answered Jan 01 '26 10:01

bigbounty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!