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

Viewed 5076

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?"

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

Related