I am trying to plot an encircling area in a scatter plot with Matplotlib, and I want to smooth a Convex Hull like an ellipse. Could anyone give me some suggestions?
Here is my code
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import patches
midwest = pd.read_csv('https://raw.githubusercontent.com/gitony0101/X4DS/main/data/midwest_filter.csv')
midwest_encircle_data = midwest.query("state=='IN'")
_, ax = plt.subplots(figsize=(10, 8))
g = sns.scatterplot(x='area',
y='poptotal',
data=midwest,
hue='state',
palette='tab10',
size='popdensity',
ax=ax)
def encircle(x, y, ax=None, **kw):
ax = ax or plt.gca()
p = np.stack([x, y], axis=1)
hull = ConvexHull(p)
poly = patches.Polygon(xy=p[hull.vertices, :], closed=True, **kw)
ax.add_patch(poly)
g.set(xlim=(0.0, 0.1),
ylim=(0, 90000),
xlabel='Area',
ylabel='Population',
title='Bubble Plot with Encircling')
x = midwest_encircle_data['area']
y = midwest_encircle_data['poptotal']
encircle(x, y, ec='k', fc='gold', alpha=0.1, ax=ax)
encircle(x, y, ec='firebrick', fc='none', linewidth=1.5, ax=ax)
plt.show()