Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a legend for facet grids

Tags:

python

seaborn

I have plotted around 10 graphs using facet grids in seaborn. How can I plot a legend in each graph? This is the current code I have:

g = sns.FacetGrid(masterdata,row="departmentid",col = "coursename",hue="resulttype",size=5, aspect=1)
g=g.map(plt.scatter, "totalscore", "semesterPercentage")

If I include plt.legend(), then the legend only appears in the last graph. How can I plot a legend in each graph in the facet grids plot? Or is there a way to plot the legend in the first graph itself, rather than the last graph? Thank you in advance for your help.

like image 429
pack24 Avatar asked Jul 06 '18 08:07

pack24


People also ask

Which plots can be plotted using faceted grids?

Multi-plot grid for plotting conditional relationships. Initialize the matplotlib figure and FacetGrid object. This class maps a dataset onto multiple axes arrayed in a grid of rows and columns that correspond to levels of variables in the dataset.

What is facet grid plot?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

How do I add a legend in ggplot2?

Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.


1 Answers

You can add a legend to each axis individually if you iterate over them. Using an example from the seaborn docs:

import seaborn as sns

tips = sns.load_dataset("tips")

g = sns.FacetGrid(tips, col="time",  hue="smoker")
g.map(plt.scatter, "total_bill", "tip", edgecolor="w")

for ax in g.axes.ravel():
    ax.legend()

The reason we have to use .ravel() is because the axes are stored in a numpy array. This gets you:

Facetgrid with individual legends

So in your case you will need to do

g = sns.FacetGrid(masterdata,row="departmentid",col = "coursename",hue="resulttype",size=5, aspect=1)
g.map(plt.scatter, "totalscore", "semesterPercentage")

for ax in g.axes.ravel():
    ax.legend()

To only show the legend in the top-left graph, you want to access the first axes in the numpy array, which will be at index [0, 0]. You can do this by doing e.g.

g = sns.FacetGrid(tips, col="time",  hue="smoker")
g.map(plt.scatter, "total_bill", "tip", edgecolor="w")

g.axes[0, 0].legend()

Which will get you: Facetgrid with legend in first axes

like image 144
asongtoruin Avatar answered Sep 29 '22 10:09

asongtoruin