Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set width and gap simultaneously in a bar chart? (Python, Plotly)

I know how to set the width of bars in a bar chart:

fig = go.Figure(data=[go.Bar(x = ['A', 'B', 'C'], y = [2, 4, 1], width=[0.5]*3)])
fig.update_layout(paper_bgcolor = 'rgba(0,0,0,0)',plot_bgcolor = 'rgba(0,0,0,0)')
fig.update_layout(bargap=0)
fig.show()

enter image description here

As you can see, the bargap is ignored. Because the width of bars has been set. Now, by removing the width property, we will get the following:

enter image description here

I desire by removing the gaps, have a thinner bar chart in the meanwhile. Now, the question is:

"How to set width and gap simultaneously in a bar chart through plotly in python?"

like image 237
OmG Avatar asked Oct 29 '25 21:10

OmG


1 Answers

There is a workaround. Check out the marimekko example at https://plotly.com/python/bar-charts/

import plotly.graph_objects as go
import numpy as np

labels = ['A', 'B', 'C']
widths = np.array([0.5]*3)
widths[1] = 0.5*4

fig = go.Figure(data=[go.Bar(x=np.cumsum(widths)-widths, width=widths, offset=0, y = [2, 4, 1])])
fig.update_layout(paper_bgcolor = 'rgba(0,0,0,0)',plot_bgcolor = 'rgba(0,0,0,0)')
fig.update_xaxes( 
    showline = True, linecolor = '#000',
    tickvals=np.cumsum(widths)-widths/2, 
    ticktext= ["%s" % (l) for l, w in zip(labels, widths)]
)
fig.update_yaxes( 
    showline = True, linecolor = '#000')
fig.update_layout()
fig.show()

Output

like image 56
Sikim Chakraborty Avatar answered Nov 01 '25 12:11

Sikim Chakraborty



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!