Open In App

How to change the position of legend using Plotly Python?

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to change the position of the legend in Plotly using Python.

The legend appears by default when variation in one object has to be depicted with reference to the other. Legend makes it easier to read a graph since it contains descriptions for the color code or keys used. By default, the legend appears on the top right corner of the plot but outside of it, but it is possible to position them as per requirement. Let us first create a regular plot so that the difference can be apparent.

Dataset Used: Click here

Example: Regular plot

Python3




# import libraries
import plotly.express as px
import pandas as pd
  
# read dataset
data = pd.read_csv("bestsellers.csv")
  
fig = px.scatter(data, x="Year", y="Price", color="Genre")
  
fig.show()


Output:

To position the legend we use the update_layout function with legend set to a dictionary that describes the attributes of a legend. anchor keys set position and x and y accommodate the margin with respect to axis.  

Syntax:

update_layout(legend=dict(yanchor, y, xanchor, x))

By setting appropriate values to the above parameters the required task can be achieved.

Example: Position the legend to the center

Python3




# import the modules
import plotly.express as px
import pandas as pd
  
# read the data
data = pd.read_csv("bestsellers.csv")
  
# scatter plot
fig = px.scatter(data, x="Year", y="Price", color="Genre")
fig.update_layout(legend=dict(y=0.5))
fig.show()


Output:

Example: Positioning legend on the plot

Python3




# import the modules
import plotly.express as px
import pandas as pd
  
# read the dataset
data = pd.read_csv("bestsellers.csv")
  
# scatter plot
fig = px.scatter(data, x="Year", y="Price", color="Genre")
# layout
fig.update_layout(legend=dict(yanchor="top", y=0.9, xanchor="left", x=0.4))
fig.show()


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads