Ejemplo: Simulación Gini#
Elaborado por: Alejandro Acosta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
plt.rcParams['figure.dpi'] = 120
plt.rcParams['savefig.dpi'] = 120
sns.set_style("whitegrid")
def simul_income(mean=1000, sd=50, size=10000):
return sorted(np.random.normal(mean, sd, size).clip(0))
def plot_income(**kwargs):
income = simul_income(**kwargs)
fig = plt.figure()
sns.histplot(income, stat='frequency', element='poly', bins=30)
plt.xlim(0,2000)
plt.ylim(0,80)
plt.close(fig)
return fig
def plot_gini(**kwargs):
income = simul_income(**kwargs)
total_income = sum(income)
bins = np.linspace(0,100, 20)
x = [np.percentile(income, i) for i in bins]
x2 = [i/100 for i in bins]
y = [np.round(sum(income*np.array([i<=x[j] for i in income]))/total_income,2) for j in range(len(bins))]
fig=plt.figure()
sns.lineplot(x=x2,y=x2)
sns.lineplot(x=x2,y=y, color='red')
plt.fill_between(x2,x2,y, color='red', alpha=0.25)
plt.ylim(0,1)
plt.xlim(0,1)
plt.close(fig)
return fig
def plot_both(**kwargs):
income = simul_income(**kwargs)
total_income = sum(income)
bins = np.linspace(0, 100, 20)
xaux = [np.percentile(income, i) for i in bins]
x = [i/100 for i in bins]
y = [np.round(sum(income*np.array([i <= xaux[j] for i in income])
)/total_income, 2) for j in range(len(bins))]
fig, ax = plt.subplots(1, 2, sharex=False, sharey=False, figsize=(10,5))
sns.histplot(income, stat='frequency', element='poly', bins=30, ax=ax[0])
ax[0].set_xlim([0, 2000])
ax[0].set_ylim([0, 80])
sns.lineplot(x=x, y=x, ax=ax[1])
sns.lineplot(x=x, y=y, color='red', ax=ax[1])
plt.fill_between(x, x, y, color='red', alpha=0.25)
ax[1].set_xlim([0, 1])
ax[1].set_ylim([0, 1])
plt.close(fig)
return fig
interact(plot_income, sd=(1,400))
<function __main__.plot_income(**kwargs)>
interact(plot_both, sd=(1,800))
<function __main__.plot_both(**kwargs)>