Search code examples
pythonplotly

Hide the legend form barchart label in Plotly


I deal with simple problem, after I added color mapping by Y value in labels have been added new value whichis useless from me. Is there any way to delete this?

        fig1=px.bar(europe_df1, x="Month End Date", y="Monthly Return",
        color=europe_df1["Monthly Return"] > 0,color_discrete_map= 
        {True: "green", False: "red"},)
        fig1.update_layout({
        'plot_bgcolor':' rgba(0, 0, 0, 0)',
        'paper_bgcolor': 'rgba(0, 0, 0, 0)',
        'font_color':'white',
        'showlegend':False,
        })

I would like to remove the 'color' label and keep only X and Y values.


Solution

  • There may be another solution that is best, but we can retrieve the graph data and update it to exclude unnecessary strings. I have modified the example in the official reference since the data is not presented.

    import plotly.express as px
    
    data_canada = px.data.gapminder().query("country == 'Canada'")
    
    fig = px.bar(data_canada,
                 x='year',
                 y='pop',
                 color=data_canada['pop'] > 20_000_000,
                 color_discrete_map={True: "green", False: "red"},
                )
    fig.update_layout({
            'plot_bgcolor':' rgba(0, 0, 0, 0)',
            'paper_bgcolor': 'rgba(0, 0, 0, 0)',
            'font_color':'white',
            'showlegend':False,
            })
    
    hovertext = fig.data[0]['hovertemplate']
    htext = hovertext.split('<br>',1)
    #print(htext)
    fig.data[0]['hovertemplate'] = htext[1]
    fig.data[1]['hovertemplate'] = htext[1]
    fig.show()
    

    enter image description here

    If no additional settings are made

    enter image description here