Customizing Legend Names in Plotly Express Line Charts
Last Updated :
23 Jul, 2025
Plotly Express is a powerful and user-friendly tool for creating interactive and visually appealing charts with Python. One common need when creating charts is customizing the legend to make it more informative and easier to understand. In this article, we will walk you through the process of changing variable or label names in the legend of a Plotly Express line chart.
Understanding the Default Legend Names
Plotly Express is a high-level interface for Plotly, designed to simplify the process of creating beautiful visualizations. It allows you to generate a wide variety of charts with just a few lines of code.
By default, Plotly Express assigns legend names based on the column names of the data. For instance, if you have a DataFrame with columns 'col1' and 'col2', the legend names will be 'col1' and 'col2' respectively. However, in many cases, these default names might not be descriptive enough or might not align with the context of the data. This is where customizing the legend names becomes essential.
Step by Step Guide: Changing Legend Labels in Plotly Line Chart
1. Using the labels
Keyword Argument
One of the simplest methods to change legend names is by using the labels
attribute in Plotly Express. This attribute allows you to map the original column names to new names.
To change legend labels in a Plotly Express line chart, follow these steps:
Step 1: Import the necessary libraries
First, import the Plotly Express and pandas libraries:
Python
import plotly.express as px
import pandas as pd
Step 2: Prepare your data
Next, prepare your data. Here, we create a simple DataFrame with sales data for two products over several years:
Python
data = {
'Year': [2020, 2021, 2022, 2023],
'Sales_A': [100, 150, 200, 250],
'Sales_B': [90, 140, 190, 240]
}
df = pd.DataFrame(data)
Step 3: Create a Plotly Express line chart
Create the line chart using Plotly Express:
Python
fig = px.line(df, x='Year', y=['Sales_A', 'Sales_B'])
Step 4: Update the legend labels
Update the legend labels to make them more informative:
Python
fig.for_each_trace(lambda trace: trace.update(name=trace.name.replace("Sales_A", "Product A Sales").replace("Sales_B", "Product B Sales")))
Output:
Output2. Using the update_traces
Method
Another approach to customize legend names is by using the update_traces
method. This method allows you to update specific properties of the traces, including the legend names.
Python
import pandas as pd
import plotly.express as px
d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
fig = px.line(df, x=df.index, y=['col1', 'col2'])
fig.update_traces({'name': 'hello'}, selector={'name': 'col1'})
fig.update_traces({'name': 'hi'}, selector={'name': 'col2'})
fig.show()
Output:
Using the update_traces MethodIn this example, the legend names are updated using the update_traces
method.
Advanced Method: Customizing Legend Names
If the labels
attribute does not work, you can manually update the legend names by modifying the figure's data traces. This approach provides more control and can handle more complex scenarios.
1. Changing the font size and color
You can change the font size and color of the legend:
Python
fig.update_layout(legend=dict(font=dict(size=12, color="pink")))
Output:
Legend color change2. Positioning the legend
You can position the legend anywhere in the chart. For example, to place it at the top right:
Python
fig.update_layout(legend=dict(x=0.1, y=0.9))
Output:
Positioning LegendUsing a Custom Function
For more complex scenarios or when dealing with multiple traces, a custom function can be created to update the legend names. This function can iterate over the traces and update the names based on a predefined dictionary.
Python
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
data = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data)
# Define name mapping
name_mapping = {'col1': 'hello', 'col2': 'hi'}
# Create a line chart with additional features
fig = go.Figure()
# Add traces for each column
for col in df.columns:
fig.add_trace(
go.Scatter(
x=df.index,
y=df[col],
mode='lines+markers',
name=name_mapping[col] if col in name_mapping else col,
line=dict(
color='blue' if col == 'col1' else 'green', # Custom line color
dash='dash' if col == 'col1' else 'dot' # Custom line style
),
marker=dict(
size=10,
symbol='circle' if col == 'col1' else 'square', # Custom marker style
color='blue' if col == 'col1' else 'green' # Custom marker color
)
)
)
# Customize layout
fig.update_layout(
title='Custom Line Chart with Updated Features',
xaxis_title='Index',
yaxis_title='Values',
legend_title='Legend',
plot_bgcolor='lightgray',
font=dict(size=14)
)
# Show the updated plot
fig.show()
Output:
Using a Custom FunctionConclusion
Customizing the legend labels in Plotly Express line charts can significantly enhance the clarity and professionalism of your visualizations. This article has provided a comprehensive guide on how to change legend labels, along with example code and additional customization options. With these techniques, you can make your charts more informative and tailored to your audience’s needs.