Ask Your Question
1

How can the legend of a Seaborn scatterplot be updated within a loop?

asked 2022-10-24 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-02-02 18:00:00 +0000

pufferfish gravatar image

One way to update the legend of a Seaborn scatterplot within a loop is to use the ax.legend() method and pass a list of the current plot labels as well as the label for the new data being added. Here is an example:

import seaborn as sns
import matplotlib.pyplot as plt

# Create empty plot
fig, ax = plt.subplots()
sns.scatterplot([], [], ax=ax)

# Loop through data and add to plot
for i in range(3):
    x = [1, 2, 3]
    y = [i+1, i+2, i+3]
    sns.scatterplot(x, y, label=f'Data {i+1}', ax=ax)

    # Update legend
    handles, labels = ax.get_legend_handles_labels()  # Get current labels
    handles.append(handles[-1])  # Fix issue with duplicate legend entries
    labels.append(f'Data {i+1}')  # Add new label
    ax.legend(handles, labels)  # Update legend

In this example, we start by creating an empty scatterplot with no data. We then loop through three iterations and add data to the plot using sns.scatterplot(). After each iteration, we update the legend by getting the current handles and labels using ax.get_legend_handles_labels(), appending the new handle and label to these lists, and then using ax.legend() to update the legend with the new labels. Note that we also had to fix an issue with duplicate legend entries by appending a copy of the last handle to the list of handles.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-24 11:00:00 +0000

Seen: 15 times

Last updated: Feb 02 '23