Search code examples
pythonplotly

Hide text on bars when value is zero (plotly)


How can I remove text on a bar having zero value in Plotly?

This is my code!

for row in range(len(st.session_state['major_vacancies_sheet'])):
            fig.add_trace(go.Bar(
                x=st.session_state['major_vacancies_sheet'].columns[2:],
                y=st.session_state['major_vacancies_sheet'].iloc[row, 2:],
                name=st.session_state['major_vacancies_sheet'].iloc[row, 1],
                text=st.session_state['major_vacancies_sheet'].iloc[row, 2:],
                hoverinfo="x+y+name",
                textposition="outside"
            )
            )

fig.update_layout(title='Bar Plots of Major Vacancies',
                          xaxis_title='Year',
                          yaxis_title='Vacancy number')

enter image description here


Solution

  • A simple way to not display zeros is to use a list comprehension with additional conditional judgments in the text settings. Citing a sample from the reference, we assume that only values greater than 20 are not to be displayed.

    import plotly.graph_objects as go
    
    x = ['Product A', 'Product B', 'Product C']
    y = [20, 14, 23]
    
    fig = go.Figure(data=[go.Bar(
                x=x, y=y,
                text=[y if y >= 20 else '' for y in y],
                textposition='outside',
            )])
    
    fig.update_yaxes(range=[0, 30])
    fig.show()
    

    enter image description here