Seaborn Tutorial
Seaborn is a Python data visualization library built on top of Matplotlib, focused on drawing various statistical graphics to make it easier to present and understand data.
The design goal of Seaborn is to simplify the process of statistical data visualization, providing high-level interfaces and beautiful default themes, enabling users to achieve complex graphics with minimal code.
Seaborn provides some simple high-level interfaces that can easily draw various statistical graphics, including scatter plots, line charts, bar charts, heatmaps, etc., and has good aesthetic effects.
Seaborn focuses on aesthetics in its design, with carefully selected default themes and color palettes to make plots more attractive.
Install Seaborn:
pip install seaborn
Seaborn provides multiple built-in themes and color palettes that can be used to change the appearance of graphics.
## Example
import seaborn as sns
# Set theme and color palette
sns.set_theme(style="whitegrid", palette="pastel")
By setting the sns.set_theme() function, you can choose different themes and templates. Here are some of the built-in themes and templates in Seaborn:
### Theme
darkgrid (default): Dark grid theme.
import seaborn as sns # Set to darkgrid theme sns.set_theme(style="darkgrid")
whitegrid: Light grid theme.
import seaborn as sns # Set to whitegrid theme sns.set_theme(style="whitegrid")
dark: Dark theme, without grid.
import seaborn as sns # Set to dark theme sns.set_theme(style="dark")
white: Light theme, without grid.
import seaborn as sns # Set to white theme sns.set_theme(style="white")
ticks: Dark theme with tick marks.
import seaborn as sns # Set to ticks theme sns.set_theme(style="ticks")
### Context
paper: Suitable for small figures, with smaller labels and lines.
import seaborn as sns # Set to paper context sns.set_theme(context="paper")
notebook (default): Suitable for laptops and similar environments, with medium-sized labels and lines.
import seaborn as sns # Set to notebook context sns.set_theme(context="notebook")
talk: Suitable for presentation slides, with large-sized labels and lines.
import seaborn as sns # Set to talk context sns.set_theme(context="talk")
poster: Suitable for posters, with very large labels and lines.
import seaborn as sns # Set to poster context sns.set_theme(context="poster")
By setting different themes and contexts, you can adjust the size of Seaborn graphics, line thickness, colors and other attributes to adapt to different plotting scenarios. These built-in themes and contexts make it easier for users to create beautiful and consistent graphics.
The following example uses Seaborn and Matplotlib to draw a simple bar chart showing the sales of different products:
## Example
import seaborn as sns
import matplotlib.pyplot as plt
# Set theme and color palette
sns.set_theme(style="darkgrid", palette="pastel")
# Sample data
products =["Product A","Product B","Product C","Product D"]
sales =[120,210,150,180]
# Create bar chart
sns.barplot(x=products, y=sales)
# Add labels and title
plt.xlabel("Products")
plt.ylabel("Sales")
plt.title("Product Sales by Category")
# Display chart
plt.show()
The result is shown in the figure below:
!(#)
* * *
## Plotting Functions
Seaborn provides multiple plotting functions for creating various statistical graphics. Here are the main plotting functions in Seaborn with corresponding examples:
### 1. Scatter Plot - sns.scatterplot()
Used to draw a scatter plot between two variables, with optional trend line.
## Example
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create a sample dataframe
data ={'A': [1,2,3,4,5],'B': [5,4,3,2,1]}
df = pd.DataFrame(data)
# Draw scatter plot
sns.scatterplot(x='A', y='B', data=df)
plt.show()
The result is shown in the figure below:
!(#)
### 2. Line Plot - sns.lineplot()
Used to draw a line chart showing how one variable changes with another.
## Example
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create a sample dataframe
data ={'X': [1,2,3,4,5],'Y': [5,4,3,2,1]}
df = pd.DataFrame(data)
# Draw line plot
sns.lineplot(x='X', y='Y', data=df)
plt.show()
The result is shown in the figure below:
!(#)
### 3. Bar Plot - sns.barplot()
Used to draw a bar chart of the mean or other aggregation function of a variable.
## Example
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create a sample dataframe
data ={'Category': ['A','B','C'],'Value': [3,7,5]}
df = pd.DataFrame(data)
# Draw bar plot
sns.barplot(x='Category', y='Value', data=df)
plt.show()
The result is shown in the figure below:
!(#)
### 4. Box Plot - sns.boxplot()
Used to draw the distribution of a variable, including median, quartiles, etc.
## Example
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create a sample dataframe
data ={'Category': ['A','A','B','B','C','C'],'Value': [3,7,5,9,2,6]}
df = pd.DataFrame(data)
# Draw box plot
sns.boxplot(x='Category', y='Value', data=df)
plt.show()
The result is shown in the figure below:
!(#)
### 5. Heatmap - sns.heatmap()
Used to draw a heatmap of matrix data, typically used to display correlation matrices.
## Example
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create a sample dataframe
data ={'A': [1,2,3,4
YouTip