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.
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
Asked: 2022-10-24 11:00:00 +0000
Seen: 16 times
Last updated: Feb 02 '23
How can I avoid labels overlapping in Pinescript?
How to create a bar chart with two sets of x-axis labels?
How can axis labels be retained while hiding the values of the tick labels?
Whenever I code the data labels for my boxplot, the y axis keeps changing.
Why is ggplot displaying decimal values in the legend when the column contains numerical values?
What is the method for creating a pie chart with three layers in R?
How can checkboxes be aligned with their corresponding labels?
How can labels be created and concealed in Excel with respect to a shipment memo?
How can the size of a ggplot2 plot be adjusted without altering the size of its axis labels?