Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.