Search code examples
pythonpython-3.xplotlyplotly-python

Hide select stacked bar text annotation in plotly.express


import pandas as pd
import plotly.express as px

df1 = pd.DataFrame()
df1['x'] = ['Product A', 'Product B', 'Product C']
df1['z'] = ['T1','T1','T1']
df1['y'] = [20, 14, 23]

df2 = pd.DataFrame()
df2['x'] = ['Product A', 'Product B', 'Product C']
df2['z'] = ['T2','T2','T2']
df2['y'] = [40, 10, 55]

df = df1.append(df2)

fig = px.bar(df,
            y="x",
            x="y",
            text='y',
            color='z',barmode='stack')
fig.show() 

I would like to show the labels for only T1, keeping within plotly.express framework because of the ease of adding facet_col features.

Current results below. I would like to remove the bar labels for T2 (red) keeping only the labels for T1 values.
enter image description here


Solution

  • You can use:

    fig.for_each_trace(lambda t: t.update(text = []) if t.name not in ['T1'] else ())
    

    And get:

    enter image description here

    Complete code:

    import pandas as pd
    import plotly.express as px
    
    df1 = pd.DataFrame()
    df1['x'] = ['Product A', 'Product B', 'Product C']
    df1['z'] = ['T1','T1','T1']
    df1['y'] = [20, 14, 23]
    
    df2 = pd.DataFrame()
    df2['x'] = ['Product A', 'Product B', 'Product C']
    df2['z'] = ['T2','T2','T2']
    df2['y'] = [40, 10, 55]
    
    df = df1.append(df2)
    
    fig = px.bar(df,
                y="x",
                x="y",
                text='y',
                color='z',barmode='stack')
    fig.show()
    
    
    # fig.for_each_trace(lambda t: print(t))
    fig.for_each_trace(lambda t: t.update(text = []) if t.name not in ['T1'] else ())
    fig.show()