<jupyter_start><jupyter_text>Histogramas en Python<jupyter_code>x = (0,1,1,1,2,2,3,7,7,7,25) # esto es una tupla inmutable
def count_elements(seq) -> dict:
    """"
    Funcion que cuenta las frecuencias
    de aparicion de cada elemento de la secuencia, 
    creando un diccionario como si fuese una 
    tabla de frecuencias
    """
    
    hist = {}
    for i in seq:
        hist[i] = hist.get(i, 0) + 1
    return hist
fAbs = count_elements(x) # frecuencias absolutas
fAbs
from collections import Counter
fAbs2 = Counter(x) # frecuencias absolutas
fAbs2
fAbs.items() == fAbs2.items() # Devuelve que es True, por ende tanto la version programada como la importada es la misma. 
def ascii_histogram(seq) -> None:
    """
    Un histograma de Frecuencias absolutas 
    colocado en horizontal y con caracteres ASCII
    """
    fAbs = count_elements(seq)
    for k in sorted(fAbs):
        print('{0:5d} {1}'.format(k, '+'*fAbs[k]))
ascii_histogram(x)
import random
random.seed(2019)
vals = [1,2,3,5,7,8,9,10]
freqs = (random.randint(5,20) for _ in vals)
data = []
for k, v in zip(vals, freqs): # usamos zip para recorrer los dos arrays, las dos variables a la vez
    data.extend([k]*v)
data
ascii_histogram(data) # histograma de frecuencias a mano.<jupyter_output>1 +++++++++
    2 ++++++++++++
    3 ++++++++++++++++++++
    5 ++++++++++
    7 ++++++++++++
    8 ++++++++++++
    9 +++++++++++++++
   10 ++++++++++++++<jupyter_text>Histogramas con NumPy<jupyter_code>import numpy as np
np.random.seed(2019)
np.set_printoptions(precision = 3)
x = np.random.laplace(loc = 10, scale = 3, size = 1000)
x[:10]
hist, bin_edges= np.histogram(x)
hist
bin_edges # estos son los intervalos de las ditribuciones de arriba
hist.size, bin_edges.size
min_edge = x.min()
max_edge = x.max()
n_bins = 10
bin_edges = np.linspace(start = min_edge, stop = max_edge, num = n_bins+1, endpoint = True)
bin_edges # construccion a mano
x = (0,1,1,1,2,2,3,7,7,7,25) # esto es una tupla inmutable
bcount = np.bincount(x) # cambiando array al primero
bcount # hay que contrastarlo con el de arriba
hist, _ = np.histogram(x, range=(0, max(x)), bins = max(x)+1)
hist # da lo mismo que la programada
np.array_equal(bcount, hist)
dict(zip(np.unique(x), bcount[bcount.nonzero()]))<jupyter_output><empty_output><jupyter_text>Visualizacion de Histogramas con Matplotlib y Pandas<jupyter_code>import matplotlib.pyplot as plt
np.random.seed(2019)
x = np.random.laplace(loc = 10, scale = 3, size = 1000)
n, bins, patches = plt.hist(x = x, bins = "auto", #aqui puedo cambiar a 12 o puedo usar scott, friedman, etc. 
                            color = "#0505a5", alpha = 0.75, rwidth= 0.85)
plt.grid(axis = "y", alpha = 0.5)
plt.xlabel("Valor")
plt.ylabel("Frecuencia")
plt.title("Un Histograma de frecuencias")
plt.text(-10, 80, r'$\mu = 10, b = 3$')
maxfreq = n.max()
plt.ylim(ymax = np.ceil(maxfreq/10)*10 if maxfreq%10 else maxfreq + 10)
n
bins
patches
import pandas as pd
size, scale = 1000, 10
data = pd.Series(np.random.gamma(scale, size = size))
data.plot.hist(grid = True, bins = 20, rwidth = 0.9, color = "#d52675")
plt.title("Distribucion Gamma")
plt.xlabel("Valores")
plt.ylabel("Frecuencias")
plt.grid(axis = "y", alpha = 0.75)<jupyter_output><empty_output><jupyter_text>Funciones de densidad y de Probabilidad<jupyter_code>mu = 10, 20
sigma = 5, 2
dist = pd.DataFrame(np.random.normal(loc = mu, scale = sigma, size = (1000, 2)), columns = ['x1', 'x2'])
dist.agg(['min', 'max', 'mean', 'std']).round(decimals = 2)
fig, ax = plt.subplots()
dist.plot.kde(ax=ax, legend = False, title = "Histograma de dos normales")
dist.plot.hist(density = True, ax = ax)
ax.set_ylabel("Probabilidad")
ax.grid(axis = "y", alpha = 0.75)
ax.set_facecolor("#d5d5d5")
from scipy import stats
dist = stats.norm() # distribucion normal teorica N(0,1) ~ exp(-x**2/2)/sqrt(2*pi)
sample = dist.rvs(size = 1000)
stats.norm.ppf(0.01)
stats.norm.ppf(0.99)
x = np.linspace(start = stats.norm.ppf(0.01), stop = stats.norm.ppf(0.99), num = 250)
gkde = stats.gaussian_kde(dataset = sample)
fig, ax = plt.subplots()
ax.plot(x, dist.pdf(x), linestyle = "solid", c = "red", lw = 3, alpha = 0.8, label = "Distribucion normal teorica")
ax.plot(x, gkde.evaluate(x), linestyle = "dashed", c = "green", lw = 2, label = "Probablity Density Function con KDE")
ax.legend(loc = "best", frameon = False)
ax.set_title("Normal analitica vs Estimada")
ax.set_ylabel("Probabilidad")
ax.text(-2., 0.35, r'$f(x) = \frac{e^{-x^2/2}}{\sqrt{2\pi}}$', fontsize = 14)<jupyter_output><empty_output><jupyter_text>Histogramas con Seaborn<jupyter_code>import seaborn as sns
import pandas.util.testing as tm
sns.distplot(data)
np.random.seed(2019)
x = np.random.laplace(loc = 10, scale = 3, size = 1000)
sns.set_style("darkgrid")
sns.distplot(x)
sns.distplot(data, fit = stats.laplace, kde = False) # para ver como se deberia de ajustar a una funcion dada.<jupyter_output><empty_output><jupyter_text>Otras formas<jupyter_code>data2 = np.random.choice(np.arange(10), size = 10000, p = np.linspace(1,11,10)/60)
s = pd.Series(data2)
s.value_counts()
s.value_counts(normalize = True)<jupyter_output><empty_output><jupyter_text>Distribuciones de Frecuencia, homologo de R.<jupyter_code>ages = pd.Series([1,1,3,5,6,8,9,10,12,15,18,18,20,25,30,40,51,52,70])
bins = (0,10,15,18,21, np.inf)
labels = ('infancia', 'preadolescencia', 'adolescencia', 'universitario', 'adulto')
groups = pd.cut(ages, bins = bins, labels = labels)
groups
groups.value_counts()
pd.concat((ages, groups), axis = 1).rename(columns = {0:"age", 1:"group"})<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17043821839080459, 'fraction_numerical': 0.04705459770114943, 'mean_word_length': 4.837526205450734, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 30, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '433500', 'license': 'CC0-1.0', 'n_tokens_mistral': 2399, 'n_tokens_neox': 2212, 'n_words': 530, 'path': 'Basic_python/Histogramas_y_distribuciones.ipynb', 'repo_name': 'levraines/Portfolio', 'size': '5568'}