Public account: You and the cabin by: Peter Editor: Peter
Hello, I’m Peter
It has been a long time since I updated a Plotly related article. The topic I chose was “Playing with Plotly legend Settings”, which is a topic I’ve been thinking about writing about for a long time. The main content of this article is:
Official website: plotly.com/python/lege…
Serialized article by Plotly
The Plotly article has been updated to article 16. Please read it. Recommend a few articles:
Import libraries and data
The data mainly used in this article is consumption data:
import pandas as pd
import numpy as np
import plotly_express as px
import plotly.graph_objects as go
# Consumption data
tips = px.data.tips()
tips.head()
Copy the code
Number of legend elements
It is mainly a legend composed of a single element and multiple elements.
A single element
fig = px.scatter(
tips, # database
x="total_bill".# xy
y="tip",
color="sex" # Legend is distinguished by color
)
fig.show()
Copy the code
A legend composed of multiple elements
When multiple elements are distinguished at the same time, different shapes are generated to display data:
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex".# color and tag to distinguish
symbol="smoker"
)
fig.show()
Copy the code
Change the legend name
With plotly_express, the labels parameter is used to change the legend name
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex".# color and markup; Symbol mainly controls shape
symbol="smoker".# Change the default legend name with labels
labels={"sex": "Gender"."smoker": "Smokes"})
fig.show()
Copy the code
You can also generate a graph with more than one cut graph:
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex",
symbol="smoker",
facet_col="time".# The column element of the section diagram
# change the legend name
labels={"sex": "Gender"."smoker": "Smokes"})
fig.show()
Copy the code
Set the legend order
Plot by plotly_express
The legend order is set with the legend. Traceorder parameter
fig = px.bar(
tips, # data frame
x="day".# xy
y="total_bill",
color="smoker".# color
barmode="stack".# Bar chart pattern
facet_col="sex".# The column element of the section diagram
category_orders={"day": ["Thur"."Fri"."Sat"."Sun"].# Custom order
"smoker": ["Yes"."No"]."sex": ["Male"."Female"]})
fig.update_layout(legend_traceorder="reversed") # set order
fig.show()
Copy the code
⚠️ defaults to the order in which the fields of the real legend appear in the raw data:
fig = px.bar(
tips, # data frame
x="day".# xy
y="total_bill",
color="smoker".# color
barmode="stack".# Bar chart pattern
facet_col="sex".# The column element of the section diagram
)
fig.show()
Copy the code
Plot with Plotly. Graph_objects
We set the order primarily through metrics Legendrank. Note: Plotly must be V5.0 or later
pip install --upgrade plotly # Upgrade version
Copy the code
If we don’t use the Legendrank parameter:
fig = go.Figure()
# Add 4 different track data
fig.add_trace(go.Bar(name="first", x=["a"."b"], y=[21.27]))
fig.add_trace(go.Bar(name="second", x=["a"."b"], y=[32.18]))
fig.add_trace(go.Bar(name="third", x=["a"."b"], y=[11.32]))
fig.add_trace(go.Bar(name="fourth", x=["a"."b"], y=[21.13]))
fig.show()
Copy the code
The order in which the legends appear above is the order of first, second, third and fourth, that is, the order in which track data is added.
Here we use the Legendrank parameter:
fig = go.Figure()
# Add 4 different track data
fig.add_trace(go.Bar(name="second".# 2
x=["a"."b"],
y=[32.18],
legendrank=2))
fig.add_trace(go.Bar(name="third".# 3
x=["a"."b"],
y=[11.32],
legendrank=3))
fig.add_trace(go.Bar(name="first".# 1
x=["a"."b"],
y=[21.27],
legendrank=1))
fig.add_trace(go.Bar(name="fourth".# 4
x=["a"."b"],
y=[21.13],
legendrank=4))
fig.show()
Copy the code
The order in which trace is added varies from first to second. In fact, it still sorts according to legendrank parameters
Show and hide legends
All of the above graphics are shown as legends by default, we can also hide them:
# Hide legends
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex",
symbol="smoker"
)
fig.update_layout(showlegend=False) # Hide the legend element
fig.show()
Copy the code
Legend location
Legends are on the right by default, and we can use arguments to change the legend position
# Default: Legend in the upper right corner
fig = px.scatter(
tips,
x="total_bill",
y="tip",
size="tip",
color="sex".# color and tag to distinguish
symbol="smoker"
)
fig.show()
Copy the code
Change the position of legend by setting parameters:
# default
fig = px.scatter(
tips,
x="total_bill",
y="tip",
size="tip",
color="sex".# color and tag to distinguish
symbol="smoker"
)
# change by position parameter
fig.update_layout(legend=dict(
yanchor="top".# top of the Y-axis
y=0.99,
xanchor="left".The X-axis is to the left
x=0.01
))
fig.show()
Copy the code
Legend level
The default legend is vertical display, with the parameter orientation to achieve horizontal display. This horizontal display is useful when there is a lot of categorization of legends.
This example uses GDP data from Plotly:
The default legend is vertical:
df = px.data.gapminder().query("year==2007") # select 2007 data
fig = px.scatter(
df, # Data box and x and y axis data
x="gdpPercap",
y="lifeExp",
color="continent".# color
size="pop".# size
size_max=45) A maximum #
fig.update_layout(legend=dict(
Orientation ="h"
yanchor="bottom".# set the position and distance of the xy axis respectively
y=1.02,
xanchor="right",
x=1
))
fig.show()
Copy the code
Now let’s turn on the horizontal display legend:
# Enable horizontal display
fig = px.scatter(
df,
x="gdpPercap",
y="lifeExp",
color="continent",
size="pop",
size_max=45)
fig.update_layout(legend=dict(
orientation="h".# Enable horizontal display
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
))
fig.show()
Copy the code
Legend personalized display
fig = px.scatter(
df,
x="gdpPercap",
y="lifeExp",
color="continent",
size="pop",
size_max=45
)
fig.update_layout(
legend=dict(
x=82..# Set the legend position
y=0,
traceorder="reversed",
title_font_family="Times New Roman".# legend title font
font=dict( # legend font
family="Courier",
size=13,
color="red" # Color: red
),
bgcolor="LightSteelBlue".# Legend background color
bordercolor="Black".# Legend border color and width
borderwidth=2
)
)
fig.show()
Copy the code
Graph Objects sets the legend
The following examples use plotly. Graph_objects to illustrate the Settings:
- The name of the legend
The name of the legend
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1.2.3.4.5],
y=[1.2.3.4.5],
name="Figure 1" # legend name
))
fig.add_trace(go.Scatter(
x=[1.2.3.4.5],
y=[5.4.3.2.1],
name=Figure 2 "" # legend name
))
fig.show()
Copy the code
Legend title
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1.2.3.4.5],
y=[1.2.3.4.5],
name="Figure 1"
))
fig.add_trace(go.Scatter(
x=[1.2.3.4.5],
y=[5.4.3.2.1],
name=Figure 2 ""
))
# Key parameter: Set the legend title
fig.update_layout(legend_title_text='Legend heading')
fig.show()
Copy the code
Show or hide legends
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=list(range(5)),
y=list(range(5)),
showlegend=False # do not display a legend for this trajectory
))
fig.add_trace(go.Scatter(
x=list(range(5)),
y=list(range(5[: : -))1],
))
fig.update_layout(showlegend=True) # Overall legend display
fig.show()
Copy the code
Sets the legend element size
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=list(range(5)),
y=list(range(5)),
mode='markers+lines'.# Mode selection
marker={'size':10} # tag size
))
fig.add_trace(go.Scatter(
x=list(range(5)),
y=[5.4.3.2.1],
mode='lines+markers',
marker={'size':50}
))
fig.update_layout(legend= {'itemsizing': 'constant'}) # Trace and constant Settings
fig.show()
Copy the code
When Itemsizing is set to constant:
When Itemsizing is trace: