0

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()

enter image description here

ivaquero
  • 69
  • 6
  • 1
    Which is the _right way_ to rotate the ellipse? Has it to be simply horizontal? Or rotated by a known angle `theta`? – Zephyr Sep 02 '21 at 06:28
  • [Plot Ellipse with matplotlib.pyplot (Python)](https://stackoverflow.com/questions/10952060/plot-ellipse-with-matplotlib-pyplot-python): The second part of this [answer](https://stackoverflow.com/a/48409811/7758804), but it doesn't use patch.Ellipse, [Matplotlib patches ellipse angle query](https://stackoverflow.com/questions/25160056/matplotlib-patches-ellipse-angle-query): the question shows how to rotate the ellipse. – Trenton McKinney Sep 02 '21 at 15:04
  • It seems like rotation is non-trivial: https://matplotlib.org/stable/gallery/units/ellipse_with_units.html & https://matplotlib.org/stable/gallery/statistics/confidence_ellipse.html – Trenton McKinney Sep 02 '21 at 15:06
  • @Zephyr Thank you for your reply, I added more details to description of my question. – ivaquero Sep 03 '21 at 09:05
  • @TrentonMcKinney Thank you. I read the article provided by Matplotlib. Those examples plot the confidence interval, while mine is to plot the max values of ranges. I haven't got inspiration from the examples yet, and I don't understand Affine2D well. – ivaquero Sep 03 '21 at 09:11

0 Answers0