There are gaps between the y axes and the bar/line data in my graph (see screenshot). I have seen similar posts fixing this by changing the range of the x axis, but my x axis data is categorical (a string value) in this case. Iβve already tried setting fig.update_xaxes(type='category')
My suggestion solution is to set xaxis rangemode to "tozero" and define explicitly range value.
Set min range to(-1*custom_xaxis_pad) ,a negatif value so it will give left padding ,because data point will start from zero.
Set maxrange to len_x+(custom_xaxis_pad-1).
By adding custom padding to length of index , it will give right padding configuration.
# Get length of index (rows)
# Assuming `grouped` is pandas Dataframe
len_x = len(grouped.index)
# Set Custom Xaxis Padding
# you can adjust custom x axis padding by changing its value
custom_xaxis_pad = 1
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(x=grouped['long_name'], y=grouped['avg_speed'], name="Average Speed", mode='lines+markers'),
secondary_y=True
)
fig.add_trace(
go.Bar(x=grouped['long_name'], y=grouped['num_trips'], name='Num Trips', marker={'color': 'lightpink'}),
secondary_y=False
)
# Set rangemode to `tozero`, which data point will start from zero.
# Specify range explicitly using `range` keyword.
# Set min range to `(-1*custom_xaxis_pad)` ,a negatif value so it will give left padding
# because data point will start from zero.
# Set max range to `len_x+(custom_xaxis_pad-1)`, so it will set right padding .
fig.update_layout(
xaxis = dict(
rangemode= 'tozero',
range=[(-1*custom_xaxis_pad),len_x+(custom_xaxis_pad-1)]
)
)
fig.show()