Reverse the order of a legend in Python – Seaborn
Let’s learn to reverse the order of a legend in Python using seaborn.
Seaborn is a well-used Python library that amplifies Matplotlib’s capabilities by giving developers more tools to create appealing and instructive visualizations. Legend is an element of the plot as it offers answers to the depicted data. legends are used in Seaborn to answer questions about the appearing data. Fundamentally, it contains details about the possible groups, classes, or features conveyed by color. These legends typically provide labels for different hues and markers used in the plot.
First, we start by importing the required libraries.
import seaborn as sns
We continue by loading an example dataset called “glue” from the Seaborn dataset repository using the load_dataset()
function. Creating a bar plot using Seaborn is done thereafter.
glue = sns.load_dataset("glue") ax=sns.barplot(x="Year", y="Score", hue="Encoder", data=glue)
We can get the handles and labels linked to the legend of the plot with the get_legend_handles_labels()
method on the axes object ax.
handles, labels = ax.get_legend_handles_labels()
We use Python’s reversed()
function to reverse the order of the legend handles and legends we obtained in the previous step. Lastly, create a new legend with the reversed order.
reversed_handles = list(reversed(handles)) reversed_labels = list(reversed(labels)) ax.legend(reversed_handles, reversed_labels, title="Encoder")
This is the plot before reversing the order.
This is the plot after reversing the order.
This is how we can reverse the order of legend in Python using Seaborn.
Leave a Reply