为刻面网格绘制图例 [英] Plotting a legend for facet grids
问题描述
我在 seaborn 中使用分面网格绘制了大约 10 个图形.如何在每个图中绘制图例?这是我当前的代码:
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")
如果我包含 plt.legend()
,那么图例只会出现在最后一张图中.如何在分面网格图中的每个图中绘制图例?或者有没有办法在第一个图形本身而不是最后一个图形中绘制图例?预先感谢您的帮助.
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.
推荐答案
如果对每个轴进行迭代,则可以分别向它们添加图例.使用来自 seaborn 文档的示例:
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()
我们必须使用 .ravel()
的原因是因为轴存储在 numpy
数组中.这让你:
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()
要仅在左上角显示图例,您需要访问 numpy
数组中的第一个 axes
,该数组位于索引 [0, 0]
.你可以这样做,例如
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()
这会让你:
这篇关于为刻面网格绘制图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!