CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-seaborn

Statistical data visualization library for Python built on matplotlib

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

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.

Capabilities

Plot Customization

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
    """

Legend Management

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)
    """

Color Manipulation

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
    """

Dataset Loading

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
    """

Visualization Utilities

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.
    """

Usage Examples

Despine Plots

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()

Move Legend

# 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()

Color Manipulation

# 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()

Dataset Loading

# 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}")

Palette Visualization

# 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()

Multi-Panel Plot Styling

# 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()

Color Palette with Desaturation

# 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()

Comprehensive Dataset Exploration

# 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()

Available Example Datasets

Common datasets available through load_dataset():

  • tips: Restaurant tip data with bill amounts and customer info
  • flights: Passenger numbers over time (time series)
  • iris: Classic iris flower measurements dataset
  • titanic: Titanic passenger survival data
  • penguins: Palmer penguins morphological data
  • mpg: Car fuel efficiency data
  • exercise: Exercise and heart rate data
  • fmri: fMRI brain scan data
  • attention: Psychology attention experiment data
  • car_crashes: US state car crash statistics
  • diamonds: Diamond characteristics and prices
  • dots: Dot motion perception experiment
  • gammas: Gamma-ray burst data
  • geyser: Old Faithful geyser eruption data
  • taxis: NYC taxi trip data

Types

# 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 names

Install with Tessl CLI

npx tessl i tessl/pypi-seaborn

docs

categorical-plots.md

color-palettes.md

distribution-plots.md

grid-plots.md

index.md

interactive-widgets.md

matrix-plots.md

objects-interface.md

relational-plots.md

styling-themes.md

utilities.md

tile.json