Plotting a legend for facet grids

人盡茶涼 提交于 2020-05-13 06:12:52

问题


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.


回答1:


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:



来源:https://stackoverflow.com/questions/51206343/plotting-a-legend-for-facet-grids

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!