CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-spyndex

Awesome Spectral Indices in Python - comprehensive library for computing spectral indices from remote sensing data

Overview
Eval results
Files

plotting.mddocs/

Visualization and Plotting

Built-in visualization tools for exploring spectral index behavior and parameter sensitivity. Provides heatmap visualizations showing index values across parameter ranges, enabling visual analysis of spectral index characteristics and band sensitivity.

Capabilities

Spectral Index Heatmaps

Creates color-encoded matrix visualizations showing all possible spectral index values across two varying parameters, with other parameters held constant.

def heatmap(
    index: str,
    x: str,
    y: str,
    params: Optional[dict] = None,
    online: bool = False,
    **kwargs
):
    """
    Plot all possible index values as a color-encoded matrix.

    Parameters:
    - index: Spectral index name to visualize
    - x: Band/parameter name for x-axis  
    - y: Band/parameter name for y-axis
    - params: Dictionary of fixed parameters for other required bands/parameters
    - online: Whether to retrieve most recent index list from GitHub
    - **kwargs: Additional arguments passed to seaborn.heatmap()

    Returns:
    matplotlib.axes.Axes: Matplotlib Axes object with the index heatmap
    """

Usage Examples:

import spyndex.plot
import matplotlib.pyplot as plt

# Simple NDVI heatmap (NIR vs Red)
ax = spyndex.plot.heatmap(
    index="NDVI",
    x="N",  # Near-infrared on x-axis
    y="R",  # Red on y-axis
    cmap="RdYlGn",  # Red-Yellow-Green colormap
    annot=True,     # Show values in cells
    fmt=".2f"       # Format to 2 decimal places
)
plt.title("NDVI Sensitivity Analysis")
plt.show()

# SAVI heatmap with fixed L parameter
ax = spyndex.plot.heatmap(
    index="SAVI",
    x="N",
    y="R", 
    params={"L": 0.5},  # Fixed soil adjustment factor
    cmap="Spectral",
    annot=True
)
plt.title("SAVI with L=0.5")
plt.show()

# EVI heatmap with multiple fixed parameters
ax = spyndex.plot.heatmap(
    index="EVI",
    x="N",
    y="R",
    params={
        "B": 0.08,  # Fixed blue reflectance
        "g": spyndex.constants.g.default,
        "C1": spyndex.constants.C1.default,
        "C2": spyndex.constants.C2.default,
        "L": spyndex.constants.L.default
    },
    cmap="viridis",
    cbar_kws={"label": "EVI Value"}
)
plt.title("EVI Sensitivity (NIR vs Red)")
plt.show()

Parameter Space Exploration

Visualizing how spectral indices behave across different parameter combinations:

import spyndex.plot
import matplotlib.pyplot as plt

# Compare different indices side by side
fig, axes = plt.subplots(1, 3, figsize=(15, 5))

indices = ["NDVI", "GNDVI", "RVI"]
titles = ["NDVI (NIR vs Red)", "GNDVI (NIR vs Green)", "RVI (NIR vs Red)"]

for i, (idx, title) in enumerate(zip(indices, titles)):
    if idx == "GNDVI":
        spyndex.plot.heatmap(
            index=idx,
            x="N", y="G",  # NIR vs Green for GNDVI
            cmap="RdYlGn",
            ax=axes[i]
        )
    else:
        spyndex.plot.heatmap(
            index=idx,
            x="N", y="R",  # NIR vs Red for others
            cmap="RdYlGn", 
            ax=axes[i]
        )
    axes[i].set_title(title)

plt.tight_layout()
plt.show()

Sensitivity Analysis

Understanding how indices respond to different reflectance conditions:

import spyndex.plot
import matplotlib.pyplot as plt

# Water index sensitivity
water_indices = ["NDWI", "MNDWI", "AWEIsh"]

fig, axes = plt.subplots(1, len(water_indices), figsize=(18, 6))

for i, idx in enumerate(water_indices):
    try:
        # Get required bands for this index
        index_obj = spyndex.indices[idx]
        bands = index_obj.bands
        
        # Create appropriate parameter mapping
        if "N" in bands and "G" in bands:
            spyndex.plot.heatmap(
                index=idx,
                x="N", y="G",
                cmap="Blues",
                ax=axes[i]
            )
        elif "N" in bands and "S1" in bands:
            spyndex.plot.heatmap(
                index=idx, 
                x="N", y="S1",
                cmap="Blues",
                ax=axes[i]
            )
        
        axes[i].set_title(f"{idx} Sensitivity")
    except:
        axes[i].text(0.5, 0.5, f"{idx}\nNot Available", 
                    ha='center', va='center', transform=axes[i].transAxes)

plt.tight_layout()
plt.show()

Custom Visualization Parameters

Advanced heatmap customization using matplotlib and seaborn parameters:

import spyndex.plot
import matplotlib.pyplot as plt
import seaborn as sns

# Highly customized heatmap
plt.figure(figsize=(10, 8))

ax = spyndex.plot.heatmap(
    index="NDVI",
    x="N",
    y="R",
    # Seaborn heatmap parameters
    cmap="RdYlGn",
    center=0,  # Center colormap at 0
    annot=True,
    fmt=".3f",
    linewidths=0.5,
    cbar_kws={
        "label": "NDVI Value",
        "shrink": 0.8
    },
    # Additional styling
    square=True,  # Square cells
    xticklabels=5,  # Show every 5th x-tick
    yticklabels=5   # Show every 5th y-tick
)

# Customize further with matplotlib
ax.set_xlabel("Near-Infrared Reflectance", fontsize=12)
ax.set_ylabel("Red Reflectance", fontsize=12)
ax.set_title("NDVI Parameter Space Analysis", fontsize=14, fontweight='bold')

# Add contour lines for specific NDVI values
import numpy as np
X, Y = np.meshgrid(np.linspace(0, 1, 11), np.linspace(0, 1, 11))
Z = (X - Y) / (X + Y)  # NDVI formula
contours = ax.contour(Z, levels=[0.2, 0.4, 0.6, 0.8], colors='black', alpha=0.4, linewidths=1)
ax.clabel(contours, inline=True, fontsize=8)

plt.tight_layout()
plt.show()

Parameter Grid Specifications

The heatmap function uses a standard parameter grid:

  • Range: 0.0 to 1.0 (typical reflectance range)
  • Resolution: 0.1 increments (11x11 grid)
  • Coverage: All combinations of the two varying parameters

This provides comprehensive coverage of typical reflectance conditions while maintaining reasonable computational efficiency.

Multi-Parameter Indices

For indices requiring more than two parameters, fixed values must be provided for additional parameters:

import spyndex.plot

# EVI requires N, R, B, g, C1, C2, L
# Fix all but two parameters
spyndex.plot.heatmap(
    index="EVI",
    x="N",    # Vary NIR
    y="B",    # Vary Blue  
    params={  # Fix others
        "R": 0.15,
        "g": 2.5,
        "C1": 6.0,
        "C2": 7.5,
        "L": 1.0
    },
    cmap="viridis"
)

# SAVI with varying L parameter
spyndex.plot.heatmap(
    index="SAVI",
    x="N",
    y="L",    # Vary soil adjustment factor
    params={
        "R": 0.15  # Fix red reflectance
    },
    cmap="RdYlGn"
)

Interpretation Guidelines

Heatmap Interpretation

  • Color intensity: Represents spectral index magnitude
  • Gradients: Show sensitivity to parameter changes
  • Patterns: Reveal index behavior characteristics
  • Boundaries: Indicate transition zones between different surface types

Common Patterns

  • NDVI: Diagonal gradient from negative (bottom-right) to positive (top-left)
  • Water indices: High values in specific parameter combinations indicating water presence
  • Vegetation indices: Peak values in high NIR, moderate red combinations
  • Burn indices: Distinctive patterns for burned vs unburned surfaces

Integration with Analysis Workflows

Heatmaps can be integrated into broader analysis workflows:

import spyndex.plot
import matplotlib.pyplot as plt

def analyze_index_sensitivity(index_name, primary_bands):
    """Comprehensive sensitivity analysis for a spectral index."""
    
    # Get index information
    index_obj = spyndex.indices[index_name]
    
    print(f"Analyzing {index_name}: {index_obj.long_name}")
    print(f"Formula: {index_obj.formula}")
    print(f"Required bands: {index_obj.bands}")
    print(f"Application domain: {index_obj.application_domain}")
    
    # Create heatmap
    fig, ax = plt.subplots(figsize=(8, 6))
    
    spyndex.plot.heatmap(
        index=index_name,
        x=primary_bands[0],
        y=primary_bands[1],
        cmap="RdYlGn",
        annot=True,
        fmt=".2f",
        ax=ax
    )
    
    ax.set_title(f"{index_name} Sensitivity Analysis")
    plt.tight_layout()
    plt.show()

# Example usage
analyze_index_sensitivity("NDVI", ["N", "R"])
analyze_index_sensitivity("GNDVI", ["N", "G"])

The plotting capabilities enable visual exploration of spectral index behavior, supporting both research applications and educational use cases in remote sensing and vegetation monitoring.

Install with Tessl CLI

npx tessl i tessl/pypi-spyndex

docs

bands.md

catalogue.md

computation.md

constants.md

datasets.md

index.md

plotting.md

tile.json