Created
January 10, 2023 15:57
-
-
Save muhammadanas0716/0108e3f8d0da4c1ac2dfc80656e8b91e to your computer and use it in GitHub Desktop.
Bubble plot with Encircling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
import matplotlib as mpl | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
# Specific imports | |
from matplotlib import patches | |
from scipy.spatial import ConvexHull | |
sns.set_style("white") | |
# Step 1: Prepare Data | |
midwest = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv") | |
# As many colors as there are unique midwest['category'] | |
categories = np.unique(midwest['category']) | |
colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))] | |
# Step 2: Draw Scatterplot with unique color for each category | |
fig = plt.figure(figsize=(16, 10), dpi= 80, facecolor='w', edgecolor='k') | |
for i, category in enumerate(categories): | |
plt.scatter('area', 'poptotal', data=midwest.loc[midwest.category==category, :], s='dot_size', c=colors[i], label=str(category), edgecolors='black', linewidths=.5) | |
# Step 3: Encircling | |
# https://stackoverflow.com/questions/44575681/how-do-i-encircle-different-data-sets-in-scatter-plot | |
def encircle(x,y, ax=None, **kw): | |
if not ax: ax=plt.gca() | |
p = np.c_[x,y] | |
hull = ConvexHull(p) | |
poly = plt.Polygon(p[hull.vertices,:], **kw) | |
ax.add_patch(poly) | |
# Select data to be encircled | |
midwest_encircle_data = midwest.loc[midwest.state=='IN', :] | |
# Draw polygon surrounding vertices | |
encircle(midwest_encircle_data.area, midwest_encircle_data.poptotal, ec="k", fc="gold", alpha=0.1) | |
encircle(midwest_encircle_data.area, midwest_encircle_data.poptotal, ec="firebrick", fc="none", linewidth=1.5) | |
# Step 4: Decorations | |
plt.gca().set(xlim=(0.0, 0.1), ylim=(0, 90000), | |
xlabel='Area', ylabel='Population') | |
plt.xticks(fontsize=12); plt.yticks(fontsize=12) | |
plt.title("Bubble Plot with Encircling", fontsize=22) | |
plt.legend(fontsize=12) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment