import seaborn as sns

# Importing datasets
tips = sns.load_dataset('tips')
iris = sns.load_dataset('iris')

In this part of the code, you’re importing the Seaborn library and loading two datasets: “tips” and “iris”. The “tips” dataset contains information about tips given to restaurant staff, while the “iris” dataset contains measurements of iris flowers.

Categorical Plots

Categorical Scatter Plot

  • Stripplot: A stripplot draws a scatterplot where one variable is categorical. It displays all data points along a category evenly distributed. It can be used to visualize the distribution of a variable within different categories.
  • Swarmplot: Similar to a stripplot, a swarmplot positions each point of the scatterplot algorithmically to avoid overlap, giving a better representation of the distribution of values.

Categorical Distribution Plots

  • Boxplot: A boxplot is a standardized way of displaying the distribution of data based on a five-number summary. It provides information about outliers, symmetry, and the tightness of data grouping.
  • Violinplot: A violinplot combines a boxplot with a kernel density estimation (KDE) plot. It shows the distribution of the data across different categories, providing a deeper insight into the distribution compared to a traditional boxplot.

Categorical Estimate Plot (Central Tendency)

  • Barplot: A barplot represents an estimate of central tendency (usually the mean) for a numerical variable with the height of bars and provides an indication of uncertainty around that estimate using error bars.
  • Pointplot: A pointplot shows point estimates and confidence intervals using scatterplot glyphs.
  • Countplot: A countplot shows the count of observations in each category using bars. It’s similar to a histogram but for categorical variables.

Figure Level Function: catplot

catplot is a figure-level function in Seaborn that combines aspects of the scatterplot, stripplot, swarmplot, boxplot, violinplot, barplot, and pointplot functions. It’s versatile and can be used to create various types of categorical plots by specifying the kind parameter.

# Scatterplot
sns.scatterplot(data=tips, x='total_bill',y='tip')

# Strip plot (axes level function)
sns.stripplot(data=tips,x='day',y='total_bill')

# Using catplot (figure level function)
sns.catplot(data=tips, x='day',y='total_bill',kind='strip')

# Jitter to avoid overlap
sns.catplot(data=tips, x='day',y='total_bill',kind='strip',jitter=0.2,hue='sex')

# Swarmplot
sns.catplot(data=tips, x='day',y='total_bill',kind='swarm')

In the above code , we demonstrate how to create scatterplots, strip plots, and swarm plots using Seaborn.

# Scatter plot
# Plotting total_bill on the x-axis and tip on the y-axis
sns.scatterplot(data=tips, x='total_bill', y='tip')

# Strip plot
# Using an axes level function to create a strip plot
# Showing the distribution of total_bill for each day
sns.stripplot(data=tips, x='day', y='total_bill')

# Using catplot
# A figure level function to create a strip plot
# Similar to sns.stripplot but with more customization options
sns.catplot(data=tips, x='day', y='total_bill', kind='strip')

# Jittered strip plot
# Adding jitter to the strip plot to avoid overlapping points
# Differentiating points by hue (sex)
sns.catplot(data=tips, x='day', y='total_bill', kind='strip', jitter=0.2, hue='sex')

# Swarm plot
# Creating a swarm plot to visualize the distribution of total_bill for each day
sns.catplot(data=tips, x='day', y='total_bill', kind='swarm')

# Swarm plot using swarmplot function directly
# Similar to the previous plot but created using the swarmplot function
sns.swarmplot(data=tips, x='day', y='total_bill')

# Swarm plot with hue
# Adding hue (sex) to the swarm plot to differentiate points by sex
sns.swarmplot(data=tips, x='day', y='total_bill', hue='sex')

In summary, the code provided demonstrates various ways to create scatter plots and categorical scatter plots using Seaborn. It includes scatter plots, strip plots, and swarm plots, with options for customization such as adding jitter and using different hues for categorical differentiation.

Boxplot

A boxplot is a standardized way of displaying the distribution of data based on a five number summary (“minimum”, first quartile [Q1], median, third quartile [Q3] and “maximum”). It can tell you about your outliers and what their values are. Boxplots can also tell you if your data is symmetrical, how tightly your data is grouped and if and how your data is skewed.

# Box plot
# Creating a box plot to visualize the distribution of total_bill for each day
sns.boxplot(data=tips, x='day', y='total_bill')

# Using catplot for box plot
# Using a figure-level function to create a box plot
# Provides additional customization options compared to sns.boxplot
sns.catplot(data=tips, x='day', y='total_bill', kind='box')

# Box plot with hue
# Creating a box plot with additional differentiation by hue (sex)
# Each box is further divided based on the values of the 'sex' variable
sns.boxplot(data=tips, x='day', y='total_bill', hue='sex')

# Single box plot for a numerical column
# Creating a single box plot for the 'total_bill' column
# Since x is not specified, it creates a box plot for a single numerical variable
sns.boxplot(data=tips, y='total_bill')

In summary, the code demonstrates different ways to create box plots using Seaborn. It includes creating basic box plots, using catplot for box plots with additional customization, adding hue for further differentiation, and creating a single box plot for a numerical column.

Violinplot


# Creating a violin plot to visualize the distribution of total_bill for each day
sns.violinplot(data=tips, x='day', y='total_bill')

# Using catplot for violinplot
# Using a figure-level function to create a violin plot
# Provides additional customization options compared to sns.violinplot
sns.catplot(data=tips, x='day', y='total_bill', kind='violin')

# Violinplot with hue
# Creating a violin plot with additional differentiation by hue (sex)
# Each violin is further divided based on the values of the 'sex' variable
sns.catplot(data=tips, x='day', y='total_bill', kind='violin', hue='sex', split=True)

# Barplot
# Creating a bar plot to visualize the mean of 'total_bill' for each 'sex' category
# Using np.min as an estimator to show the minimum value
sns.barplot(data=tips, x='sex', y='total_bill', hue='smoker', estimator=np.min)

# Barplot without error bars
# Creating a bar plot without error bars
sns.barplot(data=tips, x='sex', y='total_bill', ci=None)

# Point plot
# Creating a point plot to visualize the mean of 'total_bill' for each 'sex' category
# Each point represents the mean value with error bars indicating the confidence interval
sns.pointplot(data=tips, x='sex', y='total_bill', hue='smoker', ci=None)

# Countplot
# Creating a count plot to visualize the number of observations for each 'sex' category
# Different bars represent the count of observations for each 'day'
sns.countplot(data=tips, x='sex', hue='day')

# Faceting using catplot
# Using catplot to create a facet grid of box plots
# Each facet represents a combination of 'smoker' and 'time' categories
sns.catplot(data=tips, x='sex', y='total_bill', col='smoker', kind='box', row='time')

In summary, the code demonstrates various categorical plotting techniques using Seaborn, including violin plots, bar plots, point plots, count plots, and faceting using catplot. Each plot serves a different purpose in visualizing the data distribution or relationships between variables.

Regression Plots

  • regplot
  • lmplot

In the simplest invocation, both functions draw a scatterplot of two variables, x and y, and then fit the regression model y ~ x and plot the resulting regression line and a 95% confidence interval for that regression.



- regplot
- lmplot

In the simplest invocation, both functions draw a scatterplot of two variables, x and y, and then fit the regression model y ~ x and plot the resulting regression line and a 95% confidence interval for that regression.

# regplot
# Creating a regression plot using regplot
# Fits a regression model to the data and plots the regression line with confidence intervals
# No hue parameter available for differentiating categories
sns.regplot(data=tips, x='total_bill', y='tip')

# lmplot
# Creating a regression plot using lmplot
# Similar to regplot but allows for faceting by hue (sex)
# Fits separate regression lines for each category of the hue variable
sns.lmplot(data=tips, x='total_bill', y='tip', hue='sex')

# residplot
# Creating a residual plot using residplot
# Plots the residuals of the regression model, showing the difference between observed and predicted values
sns.residplot(data=tips, x='total_bill', y='tip')

In summary, the code demonstrates three types of regression plots using Seaborn: regplot, lmplot, and residplot. These plots are useful for visualizing the relationship between two variables and fitting regression models to the data.

A second way to plot Facet plots -> FacetGrid



# Using catplot (figure-level function) to create a facet grid of violin plots
# Each facet represents a combination of 'sex' and 'day' categories, with 'time' as additional rows
sns.catplot(data=tips, x='sex', y='total_bill', kind='violin', col='day', row='time')

# Creating a FacetGrid manually
# Using FacetGrid to create a facet grid of box plots
# Each facet represents a combination of 'day' and 'time' categories, differentiated by hue (smoker)
g = sns.FacetGrid(data=tips, col='day', row='time', hue='smoker')

# Mapping boxplot onto the facets
# Each facet contains a box plot of 'total_bill' for different 'sex' categories
g.map(sns.boxplot, 'sex', 'total_bill')

# Adding a legend to the FacetGrid
g.add_legend()

In summary, the code demonstrates two ways to create facet plots: using catplot for a quick creation of facet grids with different plot types, and using FacetGrid to manually create facet grids with customizations such as hue differentiation and specifying plot types.

Plotting Pairwise Relationship (PairGrid Vs Pairplot)



# Using pairplot to create a grid of scatterplots for pairwise relationships in the iris dataset
# Different colors represent different species (hue='species')
sns.pairplot(iris, hue='species')

# Creating a PairGrid manually
# PairGrid allows more customization compared to pairplot
g = sns.PairGrid(data=iris, hue='species')

# Mapping scatterplot onto the PairGrid
# Each subplot represents a pairwise relationship, differentiated by species
g.map(sns.scatterplot)

# Using map_diag and map_offdiag to specify different plot types for diagonal and off-diagonal subplots
# Diagonal subplots show boxplots, while off-diagonal subplots show kernel density estimates (kde)
g = sns.PairGrid(data=iris, hue='species')
g.map_diag(sns.boxplot)
g.map_offdiag(sns.kdeplot)

# Using map_diag, map_upper, and map_lower to specify different plot types for diagonal, upper, and lower subplots
# Diagonal subplots show histograms, upper subplots show kernel density estimates (kde), and lower subplots show scatterplots
g = sns.PairGrid(data=iris, hue='species')
g.map_diag(sns.histplot)
g.map_upper(sns.kdeplot)
g.map_lower(sns.scatterplot)

# Using PairGrid with specific variables
# Creating a PairGrid with only 'sepal_width' and 'petal_width' variables
g = sns.PairGrid(data=iris, hue='species', vars=['sepal_width', 'petal_width'])
g.map_diag(sns.histplot)
g.map_upper(sns.kdeplot)
g.map_lower(sns.scatterplot)

In summary, the code demonstrates two ways to plot pairwise relationships: using pairplot for a quick creation of scatterplot grids with hue differentiation, and using PairGrid for more customization options such as specifying different plot types and variables.

JointGrid Vs Jointplot



# Using jointplot to create a joint plot of 'total_bill' against 'tip' in the tips dataset
# The plot type is set to 'hist', which creates histograms for each variable and a scatterplot of the two variables
# Different colors represent different genders (hue='sex')
sns.jointplot(data=tips, x='total_bill', y='tip', kind='hist', hue='sex')

# Creating a JointGrid manually
# JointGrid allows more customization compared to jointplot
g = sns.JointGrid(data=tips, x='total_bill', y='tip')

# Plotting kernel density estimate (kde) and violin plot onto the JointGrid
# The kdeplot represents the distribution of 'total_bill' and 'tip' separately along the axes
# The violinplot represents the joint distribution of 'total_bill' and 'tip'
g.plot(sns.kdeplot, sns.violinplot)

In summary, the code demonstrates using jointplot to create a joint plot with histograms and scatterplots, and using JointGrid for more customization options such as plotting different types of plots onto the joint grid.

Utility Functions



# Get dataset names
# Returns a list of available dataset names that can be loaded using sns.load_dataset()
sns.get_dataset_names()

# Load dataset
# Loads a specific dataset from the Seaborn dataset repository
# For example, 'planets' dataset contains information about exoplanets discovered by astronomers
sns.load_dataset('planets')

In summary, these utility functions in Seaborn are used for retrieving the names of available datasets and loading specific datasets for analysis and visualization.

52 Replies to “Advance Seaborn”

  1. Hi, i think that i saw you visited my site so i came to “return the favor”.I am trying to find things to enhance my site!I suppose its ok to use a few of your ideas!!

  2. Offer a responsibility of fear and agitation in https://gamesonicexe.com, a tournament that reimagines the iconic Sonic franchise as a chilling dislike experience. Players have to outwit and outrun the malevolent Sonic.exe as they navigate through haunting levels filled with risk and dread. Can you affected by the nightmare and make oneself scarce its clutches?

  3. You defend your tranquil against hordes of zombies using a collection of plants, each with unique abilities, in https://plantszombiegame.com. The distraction’s judicious is to survive waves of zombies by strategically placing plants. This tourney challenges players to reckon at the and avail oneself of resources wisely to fend off the undead.

  4. This first-person shooter unflinching focuses on multiplayer combat. Players collide in different willing modes like Tandem join up Deathmatch and Free-For-All in Bullet Duress, using a distinct arsenal of weapons. The trick’s rational graphics and smooth gameplay manufacture https://bulletforcgames.org a spine-tingling experience for fans of FPS games.

  5. Профессиональные seo https://seo-optimizaciya-kazan.ru услуги для максимизации онлайн-видимости вашего бизнеса. Наши эксперты проведут глубокий анализ сайта, оптимизируют контент и структуру, улучшат технические аспекты и разработают индивидуальные стратегии продвижения.

  6. What i don’t understood is actually how you are no longer actually a lot more well-favored than you may be right now. You’re very intelligent. You know thus considerably in terms of this topic, produced me personally believe it from numerous numerous angles. Its like men and women aren’t involved unless it¦s something to accomplish with Woman gaga! Your personal stuffs great. At all times care for it up!

  7. Монтаж систем отопления https://fectum.pro, водоснабжения, вентиляции, канализации, очистки воды, пылеудаления, снеготаяния, гелиосистем в Краснодаре под ключ.

  8. I was very happy to find this web-site.I needed to thanks in your time for this excellent learn!! I positively having fun with every little bit of it and I have you bookmarked to check out new stuff you blog post.

  9. Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is wonderful, let alone the content!

Leave a Reply

Your email address will not be published. Required fields are marked *