Plotly (python) - do not show error bars when error is 0 or NaN

Viewed 43

The default behavior of Plotly's error bars is to show them when the error is 0 or NaN for that point. When using a bar chart, this results in a flat error bar at the top of the bar.

import plotly.express as px
import pandas as pd

data = pd.DataFrame([1, 2, 3])
sem = pd.DataFrame({'a': [math.nan, math.nan, math.nan]})
# sem = pd.DataFrame({'a': [0, 0, 0]}) # same behavior
px.bar(
    data,
    error_y=sem['a']
)

This results in a plot like this, with the error bars. enter image description here

Is it possible to remove the error bars from points where the corresponding value of the error_y dataframe is 0 or NaN? For context, in my particular case each bar represents an average. I do not want to show any bars when the average was "calculated" from one point as to not be misleading.

1 Answers

You can loop through your data and error arrays, adding a go.Bar trace without an error bar if the value in the error array is null, and adding a go.Bar trace with an error bar corresponding to the value in the error array otherwise.

import math
import plotly.graph_objects as go
import pandas as pd

data = pd.DataFrame({'x': [1, 2, 3]})
# sem = pd.DataFrame({'a': [math.nan, math.nan, math.nan]})
# sem = pd.DataFrame({'a': [0, 0, 0]}) # same behavior
em = pd.DataFrame({'a': [0.5, math.nan, 0.5]})

fig = go.Figure()
for err, y, x in zip(em['a'], data['x'], data['x'].index):
    if math.isnan(err):
        fig.add_trace(
            go.Bar(
                x=[x],
                y=[y]
            )
        )
    else:
        fig.add_trace(
            go.Bar(
                x=[x],
                y=[y],
                error_y={'type':'data', 'array':[err]}
            )
        )

fig.show()

enter image description here

Related