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.
Get hands-on with 1400+ tech skills courses.