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.
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.
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.
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.
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:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With