MissionAstro
MissionAstro

Reputation: 93

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

How do I make the bar appear when one of the value of y is zero? It just leaves a gap by default. Is there a way I can enable it to plot for zero values? I am able to see a line on the x-axis at y=0 for the same if just plotted using go.Box. I would like to see this in the Bar plot as well. So far, I set the base to zero. But that doesn't plot for y=0 either. Here is my sample code. My actual code contains multiple traces, that's why I would like to see the plot for y=0 Here is the sample python code:

 import plotly.graph_objects as go
 fig = go.Figure()
 fig.add_trace(go.Bar(x=[1, 2, 3], y=[0, 3, 2]))
 fig.show()

Upvotes: 6

Views: 5695

Answers (2)

vestland
vestland

Reputation: 61094

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

Upvotes: 6

Rob Raymond
Rob Raymond

Reputation: 31166

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

Upvotes: 3

Related Questions