<jupyter_start><jupyter_text>Seaborn In ActionSeaborn is a data visualization library that is based on **Matplotlib**. It is tightly integrated with Pandas library and provides a high level interface for making attractive and informative statistical graphics in Python.This Notebook introduces the basic and essential functions in the seaborn library. Lets go ahead and import the relevant libraries for this tutorials<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
?sns.relplot<jupyter_output><empty_output><jupyter_text>Loading the Data and Inspection<jupyter_code>cs = pd.read_csv('data/c_scores.csv')
cs
cs.sample(5)
cs.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 21 columns):
 #   Column                  Non-Null Count  Dtype  
---  ------                  --------------  -----  
 0   checking_status         979 non-null    object 
 1   duration                1000 non-null   int64  
 2   credit_history          999 non-null    object 
 3   purpose                 1000 non-null   object 
 4   credit_amount           1000 non-null   int64  
 5   savings_status          967 non-null    object 
 6   employment              968 non-null    object 
 7   installment_commitment  1000 non-null   int64  
 8   personal_status         997 non-null    object 
 9   other_parties           998 non-null    object 
 10  residence_since         1000 non-null   int64  
 11  property_magnitude      999 non-null    object 
 12  age                     1000 non-null   int64  
 13  other_payment_plans     996 non-null    object 
 14  housing                 998 non-null    o[...]<jupyter_text>Scatter Plots We shall plot the **age** and **credit_amount** columns using the **jointplot** function.<jupyter_code>sns.jointplot(x='age', y='credit_amount', data=cs)<jupyter_output><empty_output><jupyter_text>Let's plot the **age** and **credit_amount** again but this time let's break that with **job**. For this, we shall used the **relplot()**. This functions provides access to several axes-level functions that show the relationship between two variables which can also come with semantic mappings. It also come with the **kind** parameter which can be used to specify whether you want a **lineplot** or **scatterplot**. The default is **scatterplot**. The visualization below shows the relation between credit amount given to people and their ages. In addition, I am comparing it over the kind of job. Seaborn uses coloring to show which of the points represent what kind of job. The **height** and the **aspect** parameter is used to adjust the height and width of the FacetGrid. The **hue** parameter helps to group variables that will produce element with different colors. **data** parameter represents the dataset of interest.<jupyter_code>sns.relplot(x="age", y="credit_amount", height= 8, aspect=1, hue="job", data=cs)<jupyter_output><empty_output><jupyter_text>We can also plot the above visualization where we compare what it looks like over two or more categorical elements. For example, in the below visualization, we shall compare the above visualization over **class** using the **col** parameter in the **relplot()** function.<jupyter_code>sns.relplot(x="age", y="credit_amount", height= 8, aspect=1, hue="job", col='class',data=cs)<jupyter_output><empty_output><jupyter_text>Boxplots A boxplot is used to show the distribution of numerical variables and facilitates comparisons across multiple categorical variables.We would like to visualize the distribution of **age** of the customers with respect to **class**.<jupyter_code>sns.boxplot(x='class', y='age', data=cs)<jupyter_output><empty_output><jupyter_text>Let's visualize the distribution of **credit_amount** with respect to **purpose** using **class** as the **hue**<jupyter_code>fig, ax = plt.subplots(figsize=(18,7))
sns.boxplot(x='purpose', y='credit_amount', hue='class', ax = ax, data=cs)<jupyter_output><empty_output><jupyter_text>Histogram A histrogram represents the distribution of data by forming bins along the range of the data and drawing lines to represents the number of observations that fall within each bin.Let's plot the histogram of **credit_amount**.<jupyter_code>sns.distplot(cs['credit_amount'])<jupyter_output><empty_output><jupyter_text>Let's plot the histogram of the **age**<jupyter_code>sns.distplot(cs['age'])<jupyter_output><empty_output><jupyter_text>Let's get the histogram of the **credit_amount** of the customers, this time across the **class** dimension as a faceted histogram.<jupyter_code>facet = sns.FacetGrid(cs, height=6, col='class')
facet = facet.map(sns.distplot, 'credit_amount', color='r')<jupyter_output><empty_output><jupyter_text>It will however be a fantastic idea to compare the distribution of **class_amount** across **class** overlaid on the same plot.<jupyter_code>facet = sns.FacetGrid(cs, height=6, hue='class')
facet = facet.map(sns.distplot, 'credit_amount')<jupyter_output><empty_output><jupyter_text>Line Plots To make meaningful line plots, we are going to generate a dataframe to be used to help us understand line plots.We will randomly generate some dates from (1970) to (1970+36) over 12 months period. We will then go ahead and select the first 36 rows for the **duration** and **age** columns to form our new dataframe.<jupyter_code>new_series = pd.DataFrame({'time': pd.date_range('1970-12-31', periods=36, freq='12M'),
                          'duration': cs['duration'].iloc[0:36],
                          'age': cs['age'].iloc[0:36]})

new_series.head()<jupyter_output><empty_output><jupyter_text>Next, we are going to move the **duration** and the **age** columns to rows so that we can plot both on the graph. We are going to do that using the the pandas **melt()** method.The **melt()** method allows us to unpivot a dataframe  from a wide to a long format, optionally leaving the identifiers set. It takes in the dataframe you want to unpivot, the **id_vars**, identifier variable (could be single column or list of columns), the **var_name**, variable name (for the variable that are going to be unpivoted), and the **value_name**, the name of the value column.<jupyter_code>series = pd.melt(new_series, id_vars=['time'],
                var_name='Variables',
                value_name='values')

series.sample(10)
lp = sns.lineplot(x='time', y='values', hue='Variables', data=series)

#Position the legend out the graph
lp.legend(bbox_to_anchor=(1.02, 1),
          loc=2, 
          borderaxespad=0.0);
lp.set(title='Line plot of Duration and Age', xlabel='Year', ylabel='Values')<jupyter_output><empty_output><jupyter_text>Regression Plot In the regression plotting, we are going to use the **lmplot()**. This function combines the the **regplot()** and FacetGrid. It is intended as a convenient interface to fit regression models across subsets of datasets.We will use the famous iris flower dataset for the regression plot. It is available in the seaborn module.<jupyter_code>iris = sns.load_dataset('iris')
iris.sample(8)<jupyter_output><empty_output><jupyter_text>Let's plot the **sepal_length** vs the **sepal_withth** only<jupyter_code>g = sns.lmplot(x='petal_length', y='petal_width', order=1, data=iris)
g.set_axis_labels("Petal Length(mm)", "Petal Width(mm)" )<jupyter_output><empty_output><jupyter_text>Using the species, lets break the regression line with respect to the species and fit a first order regression to each species' respective data point.<jupyter_code>g = sns.lmplot(x='petal_length', y='petal_width', hue='species',height=8, order=1, data=iris)
g.set_axis_labels("Petal Length(mm)", "Petal Width(mm)" )<jupyter_output><empty_output><jupyter_text>Now, let's use the **species** as the **col**, column parameter<jupyter_code>g = sns.lmplot(x='petal_length', y='petal_width', col='species',height=10, order=1, data=iris)
g.set_axis_labels("Petal Length(mm)", "Petal Width(mm)" )<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10647571606475716, 'fraction_numerical': 0.01855541718555417, 'mean_word_length': 4.732334047109208, 'pattern_counts': {'":': 0, '<': 69, '<?xml version=': 0, '>': 69, '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': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '1776', 'license': 'Apache-2.0', 'n_tokens_mistral': 2545, 'n_tokens_neox': 2348, 'n_words': 848, 'path': 'Day 4/Seaborn In Action.ipynb', 'repo_name': 'Abuton/10-Academy-5days-Challenge', 'size': '8030'}