Now that you've learned about Seaborn's high-level interface, its styling capabilities, color palettes, and how to create basic lineplot
and scatterplot
visuals, it's time to put this knowledge into practice. We'll work through recreating some common plots, focusing on leveraging Seaborn's features for cleaner code and improved aesthetics compared to using Matplotlib alone.
First, let's ensure our environment is ready. We'll import Seaborn, Matplotlib's Pyplot module (for potential customizations like titles), NumPy (for generating sample data), and Pandas (as Seaborn often works best with DataFrames).
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Set a default Seaborn style for demonstration
sns.set_style("whitegrid")
Imagine you have data representing the temperature readings over 10 days. Let's generate some sample data and plot it using Seaborn's lineplot
.
# Generate sample data
days = np.arange(1, 11)
temperature = np.array([15, 16, 18, 17, 19, 21, 20, 22, 23, 21]) + np.random.randn(10) * 0.5
# Create the line plot using Seaborn
plt.figure(figsize=(8, 4)) # Optional: Adjust figure size
sns.lineplot(x=days, y=temperature, marker='o') # Added markers for clarity
# Add title and labels (using Matplotlib functions)
plt.title('Temperature Trend Over 10 Days')
plt.xlabel('Day')
plt.ylabel('Temperature (°C)')
# Display the plot
plt.show()
Notice how sns.lineplot
directly takes the x and y data. We used sns.set_style("whitegrid")
earlier, which automatically gives the plot a pleasant background grid. We still use plt.title
, plt.xlabel
, and plt.ylabel
from Matplotlib to add descriptive labels, demonstrating how Seaborn and Matplotlib work together. The marker='o'
argument adds circular markers to each data point on the line.
Now, let's create a scatter plot to explore the relationship between two variables, perhaps study hours and exam scores. We'll also introduce a third categorical variable, like 'study group' (Group A or Group B), using the hue
parameter.
# Generate sample data
np.random.seed(42) # for reproducibility
study_hours = np.random.rand(50) * 10
scores = 20 + 6 * study_hours + np.random.randn(50) * 8 # Base score + effect of hours + noise
study_group = np.random.choice(['Group A', 'Group B'], 50)
# Create a Pandas DataFrame (Seaborn's preferred input)
data = pd.DataFrame({
'Study Hours': study_hours,
'Exam Score': scores,
'Group': study_group
})
# Create the scatter plot using Seaborn
plt.figure(figsize=(8, 5))
sns.scatterplot(data=data, x='Study Hours', y='Exam Score', hue='Group', palette='viridis')
# Add title and labels
plt.title('Exam Score vs. Study Hours by Group')
plt.xlabel('Hours Studied')
plt.ylabel('Exam Score')
# Display the plot
plt.show()
Here, we first organized our data into a Pandas DataFrame. This is a very common pattern when working with Seaborn. We then passed the DataFrame to the data
argument of sns.scatterplot
. We specified the columns for the x-axis, y-axis, and the categorical variable for hue
simply by providing their string names.
Observe how Seaborn automatically:
This is significantly more concise than achieving the same result with Matplotlib alone, where you would typically need to plot each group separately and manually create the legend.
Seaborn makes it easy to change the overall appearance. Let's regenerate the scatter plot but change the style and context, and use a different color palette.
# Set a different style and context
sns.set_style("darkgrid")
sns.set_context("talk") # Options: 'paper', 'notebook', 'talk', 'poster'
# Recreate the scatter plot with a different palette
plt.figure(figsize=(8, 5))
sns.scatterplot(data=data, x='Study Hours', y='Exam Score', hue='Group', palette='bright')
# Add title and labels
plt.title('Exam Score vs. Study Hours (Darkgrid, Talk Context)')
plt.xlabel('Hours Studied')
plt.ylabel('Exam Score')
# Display the plot
plt.show()
# Reset to default style and context if desired for subsequent plots
# sns.set_style("whitegrid")
# sns.set_context("notebook")
By changing sns.set_style
to "darkgrid"
and sns.set_context
to "talk"
, the background, grid lines, font sizes, and line widths are adjusted globally for subsequent plots, making them suitable for a presentation. We also switched to the "bright"
color palette for a different visual effect. Experimenting with these settings is a great way to quickly tailor your plots to their intended audience and medium.
This practice session demonstrated how to use Seaborn's lineplot
and scatterplot
functions, leverage its integration with Pandas DataFrames, utilize the hue
parameter for categorical encoding, and easily customize the appearance using styles, contexts, and palettes. As you can see, Seaborn often provides a more direct path to creating statistically informative and visually appealing plots.
© 2025 ApX Machine Learning