1

As per the Plotly website, in a simple line chart one can change the legend entry from the column name to a manually specified string of text. For example, this code results in the following chart:

import pandas as pd
import plotly.express as px

df = pd.DataFrame(dict(
    x = [1, 2, 3, 4],
    y = [2, 3, 4, 3]
))

fig = px.line(
    df, 
    x="x", 
    y="y",
    width=800, height=600,
    labels={
        "y": "Series"
        }, 
    )

fig.show()

label changed:
See output: label changed

However, when one plots multiple columns to the line chart, this label specification no longer works. There is no error message, but the legend entries are simply not changed. See this example and output:

import pandas as pd
import plotly.express as px

df = pd.DataFrame(dict(
    x = [1, 2, 3, 4],
    y1 = [2, 3, 4, 3],
    y2 = [2, 4, 6, 8]
))

fig = px.line(
    df, 
    x="x", 
    y=["y1", "y2"],
    width=800, height=600,
    labels={
        "y1": "Series 1", 
        "y2": "Series 2"
        }, 
    )

fig.show()

legend entries not changed:
See output: legend entries not changed

Is this a bug, or am I missing something? Any idea how this can be fixed?

Vitalizzare
  • 4,496
  • 7
  • 13
  • 32
jandmeijer
  • 11
  • 3
  • 1
    Does this answer your question - https://stackoverflow.com/questions/64371174/plotly-how-to-change-variable-label-names-for-the-legend-in-a-plotly-express-li – Redox Jul 06 '22 at 17:00

1 Answers1

1

In case anybody read my previous post, I did some more digging and found the solution to this issue. At the heart, the labels one sees over on the right in the legend are attributes known as "names" and not "labels". Searching for how to revise those names, I came across another post about this issue with a solution Legend Label Update. Using that information, here is a revised version of your program.

import pandas as pd
import plotly.express as px

df = pd.DataFrame(dict(
    x = [1, 2, 3, 4],
    y1 = [2, 3, 4, 3],
    y2 = [2, 4, 6, 8]
))

fig = px.line(df, x="x", y=["y1", "y2"], width=800, height=600)

fig.update_layout(legend_title_text='Variable', xaxis_title="X", yaxis_title="Series")

newnames = {'y1':'Series 1', 'y2': 'Series 2'} # From the other post
fig.for_each_trace(lambda t: t.update(name = newnames[t.name]))

fig.show()

Following is a sample graph.

Sample Graph

Try that out to see if that addresses your situation.

Regards.

NoDakker
  • 3,390
  • 1
  • 10
  • 11
  • Note to jandmeijer: After researching and posting this answer, I happened to notice the comment left above. That link is the same as the one in my answer. My apologies. – NoDakker Jul 06 '22 at 21:28