Statistical data visualization library for Python built on matplotlib
—
Essential utility functions for plot customization, data loading, color manipulation, and legend management. These functions provide helpful tools for enhancing plots and working with seaborn's example datasets.
Remove spines and customize plot appearance.
def despine(
fig=None,
ax=None,
top=True,
right=True,
left=False,
bottom=False,
offset=None,
trim=False
):
"""
Remove the top and right spines from plot(s).
Parameters:
- fig: matplotlib Figure, figure to despine (if None, uses current figure)
- ax: matplotlib Axes or list, specific axes to despine
- top: bool, remove top spine
- right: bool, remove right spine
- left: bool, remove left spine
- bottom: bool, remove bottom spine
- offset: int or dict, offset spines by specified points
- trim: bool, limit spines to data range
"""Recreate and reposition plot legends with custom styling.
def move_legend(
obj,
loc,
**kwargs
):
"""
Recreate a plot's legend with a new location or visual properties.
Parameters:
- obj: matplotlib object with legend (Figure, Axes, or legend-bearing Artist)
- loc: str or int, legend location
- **kwargs: additional legend properties (title, frameon, fancybox, etc.)
Common locations:
- "upper right", "upper left", "lower left", "lower right"
- "right", "center left", "center right", "lower center", "upper center", "center"
- "outside" (seaborn-specific, places legend outside plot area)
"""Modify color properties for custom styling.
def desaturate(color, prop):
"""
Decrease the saturation channel of a color by some percent.
Parameters:
- color: str or RGB tuple, input color
- prop: float, proportion to desaturate (0-1)
Returns:
RGB tuple of desaturated color
"""
def saturate(color):
"""
Return a fully saturated color with the same hue.
Parameters:
- color: str or RGB tuple, input color
Returns:
RGB tuple of saturated color
"""
def set_hls_values(color, h=None, l=None, s=None):
"""
Independently manipulate the h, l, or s channels of a color.
Parameters:
- color: str or RGB tuple, input color
- h: float, hue value (0-360) or None to keep current
- l: float, lightness value (0-100) or None to keep current
- s: float, saturation value (0-100) or None to keep current
Returns:
RGB tuple of modified color
"""Load example datasets for learning and experimentation.
def load_dataset(name, cache=True, data_home=None, **kwargs):
"""
Load an example dataset from the online repository (or cache).
Parameters:
- name: str, dataset name
- cache: bool, cache dataset locally
- data_home: str, directory for cached datasets
- **kwargs: additional arguments passed to pandas.read_csv
Returns:
pandas.DataFrame containing the dataset
Available datasets: tips, flights, iris, titanic, attention, dots,
exercise, fmri, gammas, geyser, mpg, penguins, taxis, etc.
"""
def get_dataset_names():
"""
Report available example datasets, useful for load_dataset().
Returns:
list of str, available dataset names
"""
def get_data_home(data_home=None):
"""
Return a path to the cache directory for example datasets.
Parameters:
- data_home: str, path to use as data directory
Returns:
str, path to data directory
"""Display color palettes and novelty functions.
def palplot(pal, size=1):
"""
Plot the values in a color palette as a horizontal array.
Parameters:
- pal: list or array, color palette
- size: float, scaling factor for plot size
"""
def dogplot():
"""
Novelty function that displays random dog images.
This is an easter egg function that shows dog photos from online sources.
Requires internet connection.
"""import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# Basic plot with default spines
sns.scatterplot(data=tips, x="total_bill", y="tip")
plt.show()
# Remove top and right spines (common style)
sns.scatterplot(data=tips, x="total_bill", y="tip")
sns.despine()
plt.show()
# Remove all spines except bottom
sns.scatterplot(data=tips, x="total_bill", y="tip")
sns.despine(left=True)
plt.show()
# Offset spines from axes
sns.scatterplot(data=tips, x="total_bill", y="tip")
sns.despine(offset=10)
plt.show()# Create plot with legend
g = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="smoker")
# Move legend outside plot area
sns.move_legend(g, "upper left", bbox_to_anchor=(1, 1))
plt.show()
# Move legend to bottom with horizontal orientation
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
sns.move_legend(
plt.gca(),
"lower center",
bbox_to_anchor=(0.5, -0.15),
ncol=2
)
plt.show()# Desaturate colors
original_color = "red"
desaturated = sns.desaturate(original_color, 0.5)
# Show color comparison
colors = [original_color, desaturated]
sns.palplot(colors)
plt.title("Original vs Desaturated")
plt.show()
# Manipulate HLS values
base_color = "skyblue"
modified_colors = [
base_color,
sns.set_hls_values(base_color, h=180), # Change hue
sns.set_hls_values(base_color, l=20), # Darken
sns.set_hls_values(base_color, s=80), # More saturated
]
sns.palplot(modified_colors)
plt.show()# Load popular datasets
tips = sns.load_dataset("tips")
flights = sns.load_dataset("flights")
iris = sns.load_dataset("iris")
print(f"Tips dataset shape: {tips.shape}")
print(f"Tips columns: {list(tips.columns)}")
# See all available datasets
available_datasets = sns.get_dataset_names()
print(f"Available datasets: {available_datasets[:10]}...") # First 10
# Get data directory location
data_dir = sns.get_data_home()
print(f"Data cached at: {data_dir}")# Visualize different palettes
palettes = {
"deep": sns.color_palette("deep"),
"muted": sns.color_palette("muted"),
"bright": sns.color_palette("bright"),
"pastel": sns.color_palette("pastel"),
}
fig, axes = plt.subplots(len(palettes), 1, figsize=(8, 6))
for i, (name, palette) in enumerate(palettes.items()):
sns.palplot(palette, size=0.8)
plt.title(f"{name.title()} Palette")
if i < len(palettes) - 1:
plt.gca().set_xticks([])
plt.tight_layout()
plt.show()# Apply consistent styling across subplots
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Plot in each subplot
sns.histplot(data=tips, x="total_bill", ax=axes[0,0])
sns.boxplot(data=tips, x="day", y="total_bill", ax=axes[0,1])
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="smoker", ax=axes[1,0])
sns.barplot(data=tips, x="day", y="total_bill", ax=axes[1,1])
# Apply despine to all subplots
sns.despine(fig=fig)
plt.tight_layout()
plt.show()# Create desaturated palette for subtle coloring
base_palette = sns.color_palette("husl", 6)
desaturated_palette = [sns.desaturate(color, 0.7) for color in base_palette]
# Compare original and desaturated
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 4))
plt.subplot(2, 1, 1)
sns.palplot(base_palette)
plt.title("Original Palette")
plt.subplot(2, 1, 2)
sns.palplot(desaturated_palette)
plt.title("Desaturated Palette")
plt.tight_layout()
plt.show()# Load and explore a dataset
penguins = sns.load_dataset("penguins")
print("Dataset info:")
print(f"Shape: {penguins.shape}")
print(f"Columns: {list(penguins.columns)}")
print(f"Species: {penguins['species'].unique()}")
# Quick visualization with styling
g = sns.pairplot(penguins, hue="species", corner=True)
sns.despine()
sns.move_legend(g, "upper left", bbox_to_anchor=(0.7, 0.9))
plt.show()Common datasets available through load_dataset():
# Legend locations
LegendLocation = str | int | tuple[float, float]
# Color specifications
ColorSpec = str | tuple[float, float, float] | tuple[float, float, float, float]
# Dataset names
DatasetName = str # Any of the available dataset namesInstall with Tessl CLI
npx tessl i tessl/pypi-seaborn