简体   繁体   中英

plot ellipse in a seaborn scatter plot

I have a data frame in pandas format (pd.DataFrame) with columns = [z1,z2,Digit], and I did a scatter plot in seaborn:

dataframe = dataFrame.apply(pd.to_numeric, errors='coerce')
sns.lmplot("z1", "z2", data=dataframe, hue='Digit', fit_reg=False, size=10)
plt.show()

隐藏的空间[![] What I want to is plot an ellipse around each of these points. But I can't seem to plot an ellipse in the same figure.

I know the normal way to plot an ellipse is like:

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

elps = Ellipse((0, 0), 4, 2,edgecolor='b',facecolor='none')
a = plt.subplot(111, aspect='equal')
a.add_artist(elps)
plt.xlim(-4, 4)
plt.ylim(-4, 4)
plt.show()

But because I have to do "a = plt.subplot(111, aspect='equal')", the plot will be on a different figure. And I also can't do:

a = sns.lmplot("z1", "z2", data=rect, hue='Digit', fit_reg=False, size=10)
a.add_artist(elps)

because the 'a' returned by sns.lmplot() is of "seaborn.axisgrid.FacetGrid" object. Any solutions? Is there anyway I can plot an ellipse without having to something like a.set_artist()?

Seaborn's lmplot() used a FacetGrid object to do the plot, and therefore your variable a = lm.lmplot(...) is a reference to that FacetGrid object.

To add your elipse, you need a refence to the Axes object. The problem is that a FacetGrid can contain multiple axes depending on how you split your data. Thankfully there is a function FacetGrid.facet_axis(row_i, col_j) which can return a reference to a specific Axes object.

In your case, you would do:

a = sns.lmplot("z1", "z2", data=rect, hue='Digit', fit_reg=False, size=10)
ax = a.facet_axis(0,0)
ax.add_artist(elps)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM