How do I display bar plot for values that are zero in plotly?

Solution 1:

It is possible to create a border using marker

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(x=[1, 2, 3], y=[0, 3, 2])).update_traces(
    marker={"line": {"width": 3, "color": "rgb(0,0,0)"}}
).update_layout(yaxis={"range": [-1, 4]})

enter image description here

Solution 2:

Bar charts come with a line around the bars that by default are set to the same color as the background. In your case '#E5ECF6'. If you change that, the line will appear as a border around each bar that will remain visible even when y = 0 for any given x.

fig.update_traces(marker_line_color = 'blue', marker_line_width = 12)

If you set the line color to match that of the bar itself, you'll get this:

Plot 1: Bars with identical fill and line colors

enter image description here

If I understand correctly, this should be pretty close to what you're trying to achieve. At least visually. I would perhaps consider adjusting the yaxis range a bit to make it a bit clearer that the y value displayed is in fact 0.

Plot 2: Adjusted y axis and separate colors

enter image description here

Complete code for Plot 1:

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=[1, 2, 3], y=[0, 3, 2], marker_color = 'blue'))
fig.update_traces(marker_line_color = 'blue', marker_line_width = 12)
fig.show()

Complete code for Plot 2:

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=[1, 2, 3], y=[0, 3, 2], marker_color =  '#00CC96'))
f = fig.full_figure_for_development(warn=False)
fig.update_traces(marker_line_color = '#636EFA', marker_line_width = 4)

fig.update_yaxes(range=[-1, 4])
fig.show()

Edit after comments

Just to verify that the line color is the same as the background color using plotly version 5.4.0

Plot 1:

enter image description here

Plot 2: Zoomed in

enter image description here