<jupyter_start><jupyter_text>Seaborn vs MatplotlibSeaborn is an API built on top of Matplotlib that offers additional features not in the base mpl package.First, let's demo styles difference between Seaborn and mpl classic.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('classic')
import numpy as np
import pandas as pd
# Create a random walk, then plot w/ Matplotlib defaults
rng = np.random.RandomState(0)
x = np.linspace(0, 10, 500)
y = np.cumsum(rng.randn(500, 6), 0)

plt.plot(x, y)
plt.legend('ABCDEF', ncol=2, loc='upper left');<jupyter_output><empty_output><jupyter_text>As stated, Seaborn is built on mpl.In fact, simply importing seaborn will alter our matplotlib defaults.<jupyter_code>import seaborn as sns
sns.set()

plt.plot(x, y)
plt.legend('ABCDEF', ncol=2, loc='upper left');<jupyter_output><empty_output><jupyter_text>Really, the magic behind seaborn is that it's just a convenient set of pre-fab'd Matplotlib routines.All it means is you don't have to re-invent the wheel by implementing all those mpl routines yourself.  Seaborn Histograms, Kernel Density Estimation (KDE), and Probability Density Functions** We didn't seed the rng for this, so expect your examples to look different than text.<jupyter_code># Plot the joint distribution of multivariate-normal vars X,Y as a histogram.
data = np.random.multivariate_normal([0, 0], [[5, 2], [2, 2]], size=2000)
data = pd.DataFrame(data, columns=['x', 'y'])

for col in 'xy':
    plt.hist(data[col], density=True, alpha=0.5)
# Get a smooth estimate of joint PDF using sns's implementation of KDE
for col in 'xy':
    sns.kdeplot(data[col], shade=True)
# Combine histogram with KDE
sns.distplot(data['x'])
sns.distplot(data['y']);
# Passing multivariate data (without splitting out vars) to kdeplot yields a 2D visualization:
sns.kdeplot(data);
# Oh that's nice, it now wants you to be explicit about the vars you're passing in,
# auto-filling axis labels accordingly.
sns.kdeplot(data['x'], data['y']);
# For joint distributions / marginal distributions, use sns.jointplot()
with sns.axes_style('white'):
    sns.jointplot('x','y', data, kind='kde');<jupyter_output><empty_output><jupyter_text>^^ Mine is outputting differently, does not include summary stats at top-right corner<jupyter_code>with sns.axes_style('white'):
    sns.jointplot('x', 'y', data, kind='hex')<jupyter_output><empty_output><jupyter_text>Pair PlotsNow, we want to generalize joint plots to datasets of dimension > 2.Pair plots allow us to explore correlations on such higher multidimensional data by plotting pairs of values against each other.Explore by demo in the Iris dataset.<jupyter_code>iris = sns.load_dataset('iris')
iris.head()
# Note: Behavior is different than book - discrete dists automatically get resolved to continuous via KDE
sns.pairplot(iris, hue='species', height=2.5);<jupyter_output><empty_output><jupyter_text>Faceted histograms:I.e. histograms over subsets. We'll use Seaborn's FacetGrid() to accomplish this.Dataset used: restaurant staff tips<jupyter_code>tips = sns.load_dataset('tips')
tips.head()
tips['tip_pct'] = 100 * tips['tip'] / tips['total_bill']

grid = sns.FacetGrid(tips, row='sex', col='time', margin_titles=True)
grid.map(plt.hist, 'tip_pct', bins=np.linspace(0, 40, 15));<jupyter_output><empty_output><jupyter_text>Factor plots:On the same dataset, use a factor plot to view tge distribution of a parameter in a bin defined by some other param.<jupyter_code>with sns.axes_style(style='ticks'):
    g = sns.catplot("day", "total_bill", "sex", data=tips, kind="box")
    g.set_axis_labels("Day", "Total Bill");<jupyter_output><empty_output><jupyter_text>Note the use of Python's 'with' keyword.See this piece for an explanation, specifically the final example makes it quite clear the use of 'with'.https://effbot.org/zone/python-with-statement.htm  Joint distributionsShow joint distribution between different datasets w/ associated marginal distributions<jupyter_code>with sns.axes_style('white'):
    sns.jointplot("total_bill", "tip", data=tips, kind='hex')
# Demo jointplot's prefab marginal distribution KDE, and linear regression:
sns.jointplot("total_bill", "tip", data=tips, kind='reg');<jupyter_output><empty_output><jupyter_text>Bar plots:Plot time-series data using sns.catplot(). Now demoing with the Planets dataset.<jupyter_code>planets = sns.load_dataset('planets')
planets.head()
with sns.axes_style('white'):
    g = sns.factorplot("year", data=planets, aspect=2,
                       kind="count", color='steelblue')
    g.set_xticklabels(step=5)
with sns.axes_style('white'):
    g = sns.factorplot("year", data=planets, aspect=4.0, kind='count',
                       hue='method', order=range(2001, 2015))
    g.set_ylabels('Number of Planets Discovered')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12121840033153751, 'fraction_numerical': 0.010360547036883548, 'mean_word_length': 5.925394548063128, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 38, 'https://': 1, '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': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '254991', 'license': 'MIT', 'n_tokens_mistral': 1661, 'n_tokens_neox': 1552, 'n_words': 480, 'path': '4-matplotlib-ipynb/4.14-Seaborn.ipynb', 'repo_name': 'pgiardiniere/notes-PythonDataScienceHandbook', 'size': '4826'}