Patches in seaborn

2019-09-19 03:27发布

问题:

My intention is to add a patch at a specific coordinate in seaborn's lmplot :

Is there anyway to add a rectangular/square patch to lmplot?

I was able to get the plot printed out through sns.lmplot(). But when I try to add the rectangular patch using ax.add_patch() statement with relevant coordinate's, it error's out.

#Sample code to generate lmplot  and add patch   
ax= sns.lmplot('A', 'B', hue="group", data=res_me,fit_reg=False, \
              palette="Set1",size=10, aspect=1, scatter_kws={"s": 100,"linewidths":2,"edgecolor":"black"})

ax.add_patch(patches.Rectangle((0.912, 0.72), 1.02, .802,fill=False,edgecolor='green',lw=3))

I get the following error.

AttributeError: 'FacetGrid' object has no attribute 'add_patch'

So can we add patches to FacetGrid ?

回答1:

lmplot as you've learned, returns a FacetGrid, which stores all of its axes in an axes property as a 2D numpy array.

So you just need to do something like:

fg = sns.lmplot('A', 'B', hue="group", data=res_me,fit_reg=False,
              palette="Set1",size=10, aspect=1,
              scatter_kws={"s": 100,"linewidths":2,"edgecolor":"black"})

fg.axes[0, 0].add_patch(patches.Rectangle((0.912, 0.72), 1.02, 
                        0.802,fill=False,edgecolor='green',lw=3))

Note that if your FacetGrid only has one Axes object in it, you can access it directly with fg.ax