Announcing Dash Bio 1.0.0 🎉 : a one-stop-shop for bioinformatics and drug development visualizations.

Conditional coloring of go.Figure bar chart

My bar chart uses df.columns for x and df.iloc[0] values of each column for y axis.
I want the bar to be red if the value in that column is >=100.

There is a marker_colors example here but without conditions: https://plotly.com/python/bar-charts/#colored-and-styled-bar-chart

I tried this

#style chart
        colors = ['lightslategray'] * len(list(elems_df.columns))
        elems_cols = list(elems_df.columns)

        fig_elems = go.Figure([go.Bar(x=list(elems_df.columns),
                                      y=list(elems_df.iloc[0]),
                                      marker_colors=[x for x in colors if
                                                    elems_df.loc[0,col] <100
                                                    for col in elems_cols else 'crimson'])])

but getting a “statement expected” around “else”.

How can I do this?

Hi @nyck33,

this is a pure python problem and not related to plotly. Maybe have a look again on how list comprehensions work (eg. https://www.programiz.com/python-programming/list-comprehension)

this should do the work though:

marker_colors=['lightslategray' if elems_df.loc[0,col]<100 else 'crimson' for col in elems_cols]

Since your data is a dataframe, I also highly recommend you, to have a look at plotly express:

1 Like