Search code examples
pythonpandasplotlyjupytergoogle-colaboratory

Plotly scatterplot legends not displaying legend title, but with = sign for each color


Plotly refuses to display the legend like it should. In my case, the color is dictated by a datapoint's "Name". The Legend displays Name=[name of the datapoint] instead of giving the Legend the title "Name".

enter image description here

It looks like the image above, but it should look like this:

enter image description here

Like the "species" title, the title "Name" should be displayed in my case. Any help?


Solution

  • It's hard to tell exactly what's happening here without a reproducible example. To my knowledge, a proper application of px.scatter shouldn't render the result you're displaying. At least not for newer versions of Plotly. But in either case, and for full flexibility, you can run the two following lines to insert a legend title, and display only the text for each legend element that appears after the '=':

    fig.for_each_trace(lambda t: t.update(name=t.name.split("=")[-1]))
    fig.update_layout(legend_title_text = '<b>your title</b>')
    

    Plot 1 - Before corrections:

    enter image description here

    Plot 2 - After corrections:

    enter image description here

    Complete code:

    import plotly.graph_objects as go
    import plotly.express as px
    
    # data
    df = px.data.iris()
    
    # adjust data to reproduce the problem
    df['species'] = ['species=' + s for s in df['species']]
    
    # build figure
    fig = px.scatter(df, x='petal_length', y = 'petal_width', color = 'species')
    
    # change legend entries
    fig.for_each_trace(lambda t: t.update(name=t.name.split("=")[-1]))
    
    # edit title and show figure
    fig.update_layout(legend_title_text = '<b>Custom title</b>')
    fig.show()