# How to Position Legends Inside a Plot in Plotly-Python?

Data visualization is a powerful tool that allows us to understand information examples, patterns, and bits of knowledge all the more really. Plotly-Python, a flexible and intuitive plotting library, gives information researchers, specialists, and experts with the capacity to make outwardly engaging and intelligent plots.

Among the critical components of any plot is the legend, which assumes a significant part in assisting watchers with grasping the information and distinguish various components present in the representation. As a matter of course, Plotly positions legends outside the plot region, normally on the right-hand side.

While this arrangement is reasonable for some cases, there are situations where situating the legends inside the plot can significantly work on visual style, save important space, and upgrade the general client experience. In this complete aide, we will dive into different methods for situating legends inside a plot utilizing Plotly-Python.

## Understanding Legends in Plotly-Python

Before we plunge into moving legends inside the plot, we should investigate what legends do in Plotly-Python. Legends resemble little maps that assist us with translating the plot. They naturally seem when we add various traces (data series) to the plot. Each trace gets a label, and these marks are displayed in the legend to let us know what each trace represents.

As a matter of course, Plotly puts legends outside the plot, as a rule on the right side. This functions admirably as a rule, however some of the time it can make the plot look swarmed, particularly when we have many traces or a little plot. Putting legends inside the plot can make it look neater and more expert.

## Putting Legends Inside the Plot

Presently, we should figure out how to put legends inside the plot utilizing Plotly-Python. There are two basic ways of doing this:

## Utilizing the layout.legend Property

To situate the legend inside the plot, we can utilize the layout.legend property and set the x and y arranges. The x direction controls the flat position, and y controls the upward position. The qualities for x and y range from 0 to 1. For instance, (0, 0) is the bottom left corner of the plot, and (1, 1) is the upper right corner.

### Example

Here is a code to assist us with setting the legend inside the plot:

In this example, we set x=0.5 and y=0.9, and that implies the legend will be situated somewhat underneath the center point of the plot. You can change the directions on a case-by-case basis to track down the best situation for your plot.

import plotly.graph_objects as go
# Test information
x_values = [1, 2, 3, 4, 5]
y_values1 = [2, 4, 1, 5, 3]
y_values2 = [1, 3, 2, 4, 5]
# Create traces
trace1 = go.Scatter(x=x_values, y=y_values1, name='Trace 1', mode='markers')
trace2 = go.Scatter(x=x_values, y=y_values2, name='Trace 2', mode='lines')
# Create the figure
fig = go.Figure([trace1, trace2])
# Update the design to put the legend inside the plot
fig.update_layout(legend=dict(x=0.5, y=0.9))  # Change x and y facilitates on a case-by-case basis
# Show the plot
fig.show()


## Legend Situating with Auto-sizing

Some of the time, setting the x and y facilitates physically may not be great, particularly while managing different plot sizes or information. Plotly gives us another choice - utilizing auto-measuring for the legend position. We can accomplish this by consolidating the xanchor and yanchor properties with x and y.

### Example

In this example, we set x=0 and y=1 to put the legend at the upper left corner of the plot. By utilizing xanchor='left' and yanchor='top', the legend is consequently changed in view of the plot's size.

import plotly.graph_objects as go

# Test information
x_values = [1, 2, 3, 4, 5]
y_values1 = [2, 4, 1, 5, 3]
y_values2 = [1, 3, 2, 4, 5]

# Create traces
trace1 = go.Scatter(x=x_values, y=y_values1, name='Trace 1', mode='markers')
trace2 = go.Scatter(x=x_values, y=y_values2, name='Trace 2', mode='lines')

# Create the figure
fig = go.Figure([trace1, trace2])

# Update the design for auto-measuring legend position and left-top anchor
fig.update_layout(legend=dict(x=0, y=1, xanchor='left', yanchor='top'))

# Show the plot
fig.show()


## Legends Inside Subplots

Assuming you're working with subplots (different plots in a single figure), you might need to put legends inside each subplot exclusively. Plotly makes this really simple!

This is an illustration of the way to put legends inside subplots:

### Example

In this example, we utilized make_subplots() to make a 2x1 subplot grid. We added traces to each subplot utilizing add_trace(). To put the legends inside each subplot, we utilized legend=dict(x=0.5, y=-0.2, xanchor='center', yanchor='top'). Moreover, legend_orientation='h' was utilized to show the legends in a level design inside the subplots.

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Test information
x_values = [1, 2, 3, 4, 5]
y_values1 = [2, 4, 1, 5, 3]
y_values2 = [1, 3, 2, 4, 5]

# Make subplots with two rows and one column
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)

# Add traces to the subplots
fig.add_trace(go.Scatter(x=x_values, y=y_values1, name='Trace 1', mode='markers'), row=1, col=1)
fig.add_trace(go.Scatter(x=x_values, y=y_values2, name='Trace 2', mode='lines'), row=2, col=1)

# Update the design to put legends inside subplots and align them horizontally
fig.update_layout(
legend=dict(x=0.5, y=-0.2, xanchor='center', yanchor='top'), # Adjust y to move legend inside subplot
legend_orientation='h'
)

# Update axis titles
fig.update_xaxes(title_text='X Values', row=2, col=1)
fig.update_yaxes(title_text='Y Values', row=1, col=1)
fig.update_yaxes(title_text='Y Values', row=2, col=1)

# Show the plot
fig.show()


## Conclusion

Readers will acquire a thorough comprehension of positioning legends inside a plot utilizing Plotly-Python, enabling them to make visually appealing and useful information representations.

All in all, this far-reaching map on the best way to situate legends inside a plot in Plotly-Python will outfit information fans with the information and abilities expected to make stunning and intelligent perceptions. By becoming amazing at customizing legend position and utilizing advanced customizations, readers can raise their information perception abilities and really impart bits of knowledge through visual narrating.

Keep in mind, you can utilize either the layout.legend property or the auto-sizing technique with xanchor and yanchor to situate the legends inside the plot. On the off chance that you're working with subplots, you can put legends inside each subplot exclusively.

Updated on: 29-Aug-2023

843 Views

Get certified by completing the course