<jupyter_start><jupyter_text>Customizing Seaborn Plots**In this final chapter, you will learn how to add informative plot titles and axis labels, which are one of the most important parts of any data visualization! You will also learn how to customize the style of your visualizations in order to more quickly orient your audience to the key takeaways.**<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns<jupyter_output><empty_output><jupyter_text>Changing style and paletteLet's return to our dataset containing the results of a survey given to young people about their habits and preferences. We've provided the code to create a count plot of their responses to the question "How often do you listen to your parents' advice?". Now let's change the style and palette to make this plot easier to interpret.  Changing the figure style- Figure "style" includes background and axes- Preset options: "white", "dark", "whitegrid", "darkgrid", "ticks"- `sns.set_style()` Changing the palette- Figure "palette" changes the color of the main elements of the plot- `sns.set_palette()`- Use preset palettes or create a custom palette<jupyter_code>survey_data = pd.read_csv('survey_data.csv')<jupyter_output><empty_output><jupyter_text>- Set the style to "whitegrid" to help the audience determine the number of responses in each category.<jupyter_code># Set the style to "whitegrid"
sns.set_style('whitegrid')

# Create a count plot of survey responses
category_order = ["Never", "Rarely", "Sometimes", "Often", "Always"]

sns.catplot(x="Parents Advice", data=survey_data, 
            kind="count")

plt.xticks([0,1,2,3,4], category_order)
# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>- Set the color palette to the sequential palette named `"Purples"`.<jupyter_code># Set the color palette to "Purples"
sns.set_palette('Purples')

# Set the style to "whitegrid"
sns.set_style('whitegrid')

# Create a count plot of survey responses
category_order = ["Never", "Rarely", "Sometimes", "Often", "Always"]

sns.catplot(x="Parents Advice", data=survey_data, 
            kind="count")

plt.xticks([0,1,2,3,4], category_order)
# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>- Change the color palette to the diverging palette named `"RdBu"`.<jupyter_code># Change the color palette to "RdBu"
sns.set_palette('RdBu')

# Set the style to "whitegrid"
sns.set_style('whitegrid')

# Create a count plot of survey responses
category_order = ["Never", "Rarely", "Sometimes", "Often", "Always"]

sns.catplot(x="Parents Advice", data=survey_data, 
            kind="count")

plt.xticks([0,1,2,3,4], category_order)
# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*This style and diverging color palette best highlights the difference between the number of young people who usually listen to their parents' advice versus those who don't.*  Changing the scaleIn this exercise, we'll continue to look at the dataset containing responses from a survey of young people. Does the percentage of people reporting that they feel lonely vary depending on how many siblings they have? Let's find out using a bar plot, while also exploring Seaborn's four different plot scales ("contexts").  Changing the scale- Figure "context" changes the scale of the plot elements and labels- `sns.set_context()`- Smallest to largest: "paper", "notebook", "talk", "poster"<jupyter_code>conditions = [(survey_data['Siblings'] == 0), 
              ((survey_data['Siblings'] > 0) & (survey_data['Siblings'] < 3)), 
              (survey_data['Siblings'] > 2)]
values = ['0', '1 - 2', '3+']
survey_data['Number of Siblings'] = np.select(conditions, values)<jupyter_output><empty_output><jupyter_text>- Set the scale ("context") to `"paper", which is the smallest of the scale options.<jupyter_code># Set the context to "paper"
sns.set_context('paper')

# Create bar plot
sns.catplot(x="Number of Siblings", y="Loneliness",
            data=survey_data, kind="bar", order=['0', '1 - 2', '3+'])

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>- Change the context to `"notebook"` to increase the scale.<jupyter_code># Change the context to "notebook"
sns.set_context('notebook')

# Create bar plot
sns.catplot(x="Number of Siblings", y="Loneliness",
            data=survey_data, kind="bar", order=['0', '1 - 2', '3+'])

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>- Change the context to `"talk"` to increase the scale.<jupyter_code># Change the context to "talk"
sns.set_context('talk')

# Create bar plot
sns.catplot(x="Number of Siblings", y="Loneliness",
            data=survey_data, kind="bar", order=['0', '1 - 2', '3+'])

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>- Change the context to `"poster"`, which is the largest scale available.<jupyter_code># Change the context to "poster"
sns.set_context('poster')

# Create bar plot
sns.catplot(x="Number of Siblings", y="Loneliness",
            data=survey_data, kind="bar", order=['0', '1 - 2', '3+'])

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*Each context name gives Seaborn's suggestion on when to use a given plot scale (in a paper, in an iPython notebook, in a talk/presentation, or in a poster session).*  Using a custom paletteSo far, we've looked at several things in the dataset of survey responses from young people, including their internet usage, how often they listen to their parents, and how many of them report feeling lonely. However, one thing we haven't done is a basic summary of the type of people answering this survey, including their age and gender. Providing these basic summaries is always a good practice when dealing with an unfamiliar dataset. - Set the style to `"darkgrid"`.- Set a custom color palette with the hex color codes `"39A7D0"` and `"36ADA4"`.<jupyter_code>sns.set_context('notebook')

# Set the style to "darkgrid"
sns.set_style('darkgrid')

# Set a custom color palette
custom_palette = ["#39A7D0", "#36ADA4"]
sns.set_palette(custom_palette)

# Create the box plot of age distribution by gender
sns.catplot(x="Gender", y="Age", 
            data=survey_data, kind="box")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*It looks like the median age is the same for males and females, but distribution of females skews younger than the males.* ---  FacetGrids vs. AxesSubplotsIn the recent lesson, we learned that Seaborn plot functions create two different types of objects: `FacetGrid` objects and `AxesSubplot` objects. The method for adding a title to your plot will differ depending on the type of object it is.In the code provided, we've used `relplot()` with the miles per gallon dataset to create a scatter plot showing the relationship between a car's weight and its horsepower. This scatter plot is assigned to the variable name `g`. Let's identify which type of object it is.<jupyter_code>mpg = pd.read_csv('mpg.csv')<jupyter_output><empty_output><jupyter_text>- Identify what type of object plot `g` is and assign it to the variable `type_of_g`.<jupyter_code># Create scatter plot
g = sns.relplot(x="weight", y="horsepower", 
                data=mpg, kind="scatter")

# Identify plot type
type_of_g = type(g)

# Print type
print(type_of_g)<jupyter_output><class 'seaborn.axisgrid.FacetGrid'><jupyter_text>QuestionWe've just seen that `sns.relplot()` creates `FacetGrid` objects. Which other Seaborn function creates a `FacetGrid` object instead of an `AxesSubplot` object?1. `sns.catplot()`2. ~`sns.scatterplot()`~3. ~`sns.boxplot()`~4. ~`sns.countplot()`~Answer: 1. `catplot()` supports creating subplots, so it creates a `FacetGrid` object.  FacetGrid vs. AxesSubplot objectsObject Type | Plot Types | Characteristics:---|:---|:---`FacetFrid` | `relplot()` , `catplot()` | Can create subplots`AxesSubplot` | `scatterplot()`, `countplot()`, `boxplot()`, etc. | Only creates a single plot  Adding a title to a FacetGrid objectIn the previous exercise, we used `relplot()` with the miles per gallon dataset to create a scatter plot showing the relationship between a car's weight and its horsepower. This created a `FacetGrid` object. Now that we know what type of object it is, let's add a title to this plot. - Add the following title to this plot: `"Car Weight vs. Horsepower"`.<jupyter_code># Create scatter plot
g = sns.relplot(x="weight", y="horsepower", 
                data=mpg, kind="scatter")

# Add a title "Car Weight vs. Horsepower"
g.fig.suptitle('Car Weight vs. Horsepower', y=1.03)

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*It looks like a car's weight is positively correlated with its horsepower.*  Adding a title and axis labelsLet's continue to look at the miles per gallon dataset. This time we'll create a line plot to answer the question: How does the average miles per gallon achieved by cars change over time for each of the three places of origin? To improve the readability of this plot, we'll add a title and more informative axis labels.We're going to use the `lineplot()` function. Note that `lineplot()` does not support the creation of subplots, so it returns an `AxesSubplot` object instead of an `FacetGrid` object. - Add the following title to the plot: `"Average MPG Over Time"`.<jupyter_code>mpg_mean = mpg.groupby(['model_year', 'origin']).agg({'mpg':'mean'})
# Create line plot
g = sns.lineplot(x="model_year", y="mpg", 
                 data=mpg_mean, hue="origin")

# Add a title "Average MPG Over Time"
g.set_title('Average MPG Over Time')

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>- Label the x-axis as "Car Model Year" and the y-axis as "Average MPG".<jupyter_code># Create line plot
g = sns.lineplot(x="model_year", y="mpg", 
                 data=mpg_mean, hue="origin")

# Add a title "Average MPG Over Time"
g.set_title('Average MPG Over Time')

# Add x-axis and y-axis labels
g.set(xlabel='Car Model Year', ylabel='Average MPG')

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*The average miles per gallon achieved is increasing over time for all three places of origin, but the USA is always lower than Europe and Japan.*  Rotating x-tick labelsIn this exercise, we'll continue looking at the miles per gallon dataset. In the code provided, we create a point plot that displays the average acceleration for cars in each of the three places of origin. Note that the `"acceleration"` variable is the time to accelerate from 0 to 60 miles per hour, in seconds. Higher values indicate slower acceleration.Let's use this plot to practice rotating the x-tick labels. Recall that the function to rotate x-tick labels is a standalone Matplotlib function and not a function applied to the plot object itself. - Rotate the x-tick labels 90 degrees.<jupyter_code># Create point plot
sns.catplot(x='origin', y='acceleration', data=mpg, 
            kind='point', join=False, capsize=0.1)

# Rotate x-tick labels
plt.xticks(rotation=90)

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*Since higher values indicate slower acceleration, it looks like cars from Japan and Europe have significantly slower acceleration compares to the USA.* ---  Putting it all together Getting started**To import Seaborn:**```pythonimport seaborn as sns```**To import Matplotlib:**```pythonimport matplotlib.pyplot as plt```**To show a plot:**```pythonplt.show()``` Relational plots- Show the relationship between two quantitative variables- Examples: ***scatter plots, line plots***```pythonsns.relplot(x="x_variable_name",              y="y_variable_name",              data=pandas_df,              kind="scatter")``` Categorical plots- Show the distribution of a quantitative variable within categories de,ned by a categorical variable- Examples: ***bar plots, count plots, box plots, point plots***```pythonsns.catplot(x="x_variable_name",              y="y_variable_name",              data=pandas_df,              kind="bar")``` Adding a third variable (hue)- Setting `hue` will create subgroups that are displayed as different colors on a single plot. Adding a third variable (row/col)- Setting `row` and/or `col` in `relplot()` or `catplot()` will create subgroups that are displayed on separate subplots. Customization- Change the background: `sns.set_style()`- Change the main element colors: `sns.set_palette()`- Change the scale: `sns.set_context()` Adding a titleObject Type | Plot Types | How to Add Title:---|:---|:---`FacetFrid` | `relplot()` , `catplot()` | `g.fig.suptitle()``AxesSubplot` | `scatterplot()`, `countplot()`, `boxplot()`, etc. | `g.set_title()` Final touches**Add x- and y-axis labels:**```pythong.set(xlabel="new x-axis label",      ylabel="new y-axis label")```**Rotate x-tick labels:**```pythonplt.xticks(rotation=90)``` ---  Box plot with subgroupsIn this exercise, we'll look at the dataset containing responses from a survey given to young people. One of the questions asked of the young people was: "Are you interested in having pets?" Let's explore whether the distribution of ages of those answering "yes" tends to be higher or lower than those answering "no", controlling for gender. - Set the color palette to `"Blues"`.- Add subgroups to color the box plots based on `"Interested in Pets"`.- Set the title of the `FacetGrid` object `g` to "Age of Those Interested in Pets vs. Not".- Make the plot display using a Matplotlib function.<jupyter_code>survey_data.dropna(subset=['Pets'], inplace=True)
conditions = [(survey_data['Pets'] <= 3), 
              (survey_data['Pets'] > 3)]
values = ['No', 'Yes']
survey_data['Interested in Pets'] = np.select(conditions, values)
# Set palette to "Blues"
sns.set_palette('Blues')

# Adjust to add subgroups based on "Interested in Pets"
g = sns.catplot(x="Gender",
                y="Age", data=survey_data, 
                kind="box", hue='Interested in Pets')

# Set title to "Age of Those Interested in Pets vs. Not"
g.fig.suptitle('Age of Those Interested in Pets vs. Not')

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>*After controlling for gender, it looks like the age distributions of people who are interested in pets are similar than those who aren't.*  Bar plot with subgroups and subplotsIn this exercise, we'll return to our young people survey dataset and investigate whether the proportion of people who like techno music (`"Likes Techno"`) varies by their gender (`"Gender"`) or where they live (`"Village - town"`). - Set the figure style to `"dark"`.- Adjust the bar plot code to add subplots based on `"Gender"`, arranged in columns.- Add the title "Percentage of Young People Who Like Techno" to this `FacetGrid` plot.- Label the x-axis "Location of Residence" and y-axis "% Who Like Techno".<jupyter_code>survey_data.dropna(subset=['Techno'], inplace=True)
conditions = [(survey_data['Techno'] <= 3), 
              (survey_data['Techno'] > 3)]
values = [False, True]
survey_data['Likes Techno'] = np.select(conditions, values)
# Set the figure style to "dark"
sns.set_style('dark')
sns.set_palette('deep')

# Adjust to add subplots per gender
g = sns.catplot(x="Village - town", y="Likes Techno", 
                data=survey_data, kind="bar",
                col='Gender')

# Add title and axis labels
g.fig.suptitle("Percentage of Young People Who Like Techno", y=1.02)
g.set(xlabel="Location of Residence", 
      ylabel="% Who Like Techno")

# Show plot
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11348111870086351, 'fraction_numerical': 0.005090862224513468, 'mean_word_length': 4.8784090909090905, 'pattern_counts': {'":': 0, '<': 80, '<?xml version=': 0, '>': 81, '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': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '117527', 'license': 'FSFAP', 'n_tokens_mistral': 4885, 'n_tokens_neox': 4604, 'n_words': 1820, 'path': 'Data Analyst with Python/06_Introduction_to_Data_Visualization_with_Seaborn/06_4_Customizing Seaborn Plots.ipynb', 'repo_name': 'brendensong/DataCamp', 'size': '15518'}