Adding and Customizing Legends
Learn how to add and customize the legends in your Plotly figures.
Adding and customizing legends
Adding a legend improves the readability of our plot to then make more accurate interpretations of our data. In this section, we will understand the nuances of legends in Plotly Express and learn to use the graph objects module.
Legends in Plotly Express
When using Plotly Express, in this scatter plot example, we can automatically place a legend in our graph by adding a keyword argument color
, which we can pass in as a pandas series name (as a string) assuming the data_frame
argument has bee set to the correct DataFrame. In the case where color
is set to a categorical variable, the legend is comprised of discrete colors, and in the case where the color
argument is set to a continuous variable, the legend represents a colorbar.
We will explore two examples, in which both examples plot life expectancy against infant mortality. In the first example, we include a legend by coloring the scatter markers in terms of the Country Type
categorical variable. Conversely, in the second plot, we include a colorbar by coloring the scatter markers in terms of the MeanSchooling
numeric continuous variable.
Categorical variable case
First, we can see what happens when a categorical variable is added as the color.
This is executed on line 15.
# Import librariesimport plotly.express as pximport plotly.graph_objects as goimport pandas as pdimport numpy as np# Import datasethealth = pd.read_csv("/usr/local/csvfiles/health.csv")# Example 1: Legend with discrete elementsfig = px.scatter(data_frame=health, x="InfantMortality", y="Life_exp", color="Country Type")fig.show()
Continuous case
We can look at how this differs when adding a continuous variable to the color argument.
This is executed on line 15.
# Import librariesimport plotly.express as pximport plotly.graph_objects as goimport pandas as pdimport numpy as np# Import datasethealth = pd.read_csv("/usr/local/csvfiles/health.csv")# Example 2: Legend with continouous colorbarfig = px.scatter(data_frame=health, x="InfantMortality", y="Life_exp", color="MeanSchooling")fig.show()
Graph objects (categorical variable)
Here is how we can create a legend with discrete elements using graph objects:
-
Line 11: Create an empty list with all of our traces that we wish to plot.
-
In a
for
loop that iterates through every unique value in the series:a) Line 16: Filter only the rows in the DataFrame where the categorical variable is equal to the value in the loop. Store the data in a variable called
temp
.b) Lines 18–21: Create our trace using only the filtered data in
temp
, setting ...