CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-ipykernel

IPython Kernel for Jupyter - provides the core communication layer between Jupyter frontends and the Python interpreter

Pending
Overview
Eval results
Files

matplotlib-integration.mddocs/

Matplotlib Integration

Specialized support for matplotlib inline plotting, display hooks for rich output, and integration with Jupyter's display system. Enables seamless matplotlib visualization within Jupyter notebooks and other frontends.

Capabilities

Inline Backend Functions

Core functions for matplotlib inline display in Jupyter environments.

def show(close=None):
    """
    Display matplotlib figures inline.
    
    Shows all active matplotlib figures in the Jupyter frontend
    and optionally closes them after display.
    
    Parameters:
    - close (bool, optional): Whether to close figures after showing
                             If None, uses configuration default
    """

def draw_if_interactive():
    """
    Draw figures if matplotlib is in interactive mode.
    
    Triggers drawing of matplotlib figures when in interactive mode,
    ensuring plots are updated in Jupyter frontends.
    """

def flush_figures():
    """
    Flush all pending matplotlib figures.
    
    Forces display of all matplotlib figures that are ready to be shown,
    ensuring they appear in the Jupyter frontend.
    """

Backend Configuration

Functions for configuring matplotlib's inline backend behavior.

def configure_inline_support(shell, backend):
    """
    Configure matplotlib inline backend for IPython shell.
    
    Sets up matplotlib integration with the IPython shell, enabling
    inline display of plots and configuring display hooks.
    
    Parameters:
    - shell: IPython shell instance
    - backend: Matplotlib backend configuration
    """

Inline Backend Configuration Classes

Classes for managing matplotlib inline backend settings and behavior.

class InlineBackendConfig:
    """
    Configuration class for matplotlib inline backend.
    
    Manages settings for how matplotlib figures are displayed
    inline in Jupyter environments.
    """
    
    # Configuration attributes
    figure_formats: set       # Set of figure formats to use
    print_figure_kwargs: dict # Keyword arguments for figure printing
    close_figures: bool       # Whether to close figures after display
    shell: object            # Reference to IPython shell

class InlineBackend:
    """
    Main inline backend class for matplotlib integration.
    
    Handles the display and formatting of matplotlib figures
    within Jupyter notebook environments.
    """
    
    def show(self, close=None):
        """
        Show matplotlib figures inline.
        
        Parameters:
        - close (bool, optional): Whether to close after showing
        """
    
    def draw_if_interactive(self):
        """Draw figures if in interactive mode."""
    
    def flush_figures(self):
        """Flush all pending figures."""
    
    # Backend configuration
    config: InlineBackendConfig  # Backend configuration object

Usage Examples

Basic Inline Plotting

from ipykernel.pylab.backend_inline import show, flush_figures
import matplotlib.pyplot as plt
import numpy as np

# Create a simple plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Sine Wave Plot')
plt.legend()
plt.grid(True)

# Display the plot inline
show()

Multiple Figure Display

from ipykernel.pylab.backend_inline import show, flush_figures
import matplotlib.pyplot as plt
import numpy as np

# Create multiple figures
x = np.linspace(0, 10, 100)

# Figure 1: Sine wave
plt.figure(1, figsize=(8, 4))
plt.plot(x, np.sin(x), 'b-', label='sin(x)')
plt.title('Sine Wave')
plt.legend()

# Figure 2: Cosine wave  
plt.figure(2, figsize=(8, 4))
plt.plot(x, np.cos(x), 'r-', label='cos(x)')
plt.title('Cosine Wave')
plt.legend()

# Figure 3: Both waves
plt.figure(3, figsize=(10, 6))
plt.plot(x, np.sin(x), 'b-', label='sin(x)')
plt.plot(x, np.cos(x), 'r-', label='cos(x)')
plt.title('Sine and Cosine Waves')
plt.legend()

# Display all figures
flush_figures()

Interactive Plotting with Updates

from ipykernel.pylab.backend_inline import show, draw_if_interactive
import matplotlib.pyplot as plt
import numpy as np
import time

# Enable interactive mode
plt.ion()

# Create figure
fig, ax = plt.subplots(figsize=(10, 6))
x = np.linspace(0, 10, 100)

# Initial plot
line, = ax.plot(x, np.sin(x), 'b-', linewidth=2)
ax.set_xlabel('X values')
ax.set_ylabel('Y values')
ax.set_title('Animated Sine Wave')
ax.grid(True)

# Show initial plot
show()

# Animate the plot
for phase in np.linspace(0, 4*np.pi, 20):
    # Update data
    y = np.sin(x + phase)
    line.set_ydata(y)
    
    # Trigger redraw
    draw_if_interactive()
    
    # Small delay for animation effect
    time.sleep(0.1)

plt.ioff()  # Turn off interactive mode

Custom Figure Configuration

from ipykernel.pylab.backend_inline import configure_inline_support, show
from ipykernel.pylab.config import InlineBackend, InlineBackendConfig
import matplotlib.pyplot as plt
import numpy as np

# Configure matplotlib for high-quality inline display
config = InlineBackendConfig()
config.figure_formats = {'png', 'svg'}  # Use both PNG and SVG
config.print_figure_kwargs = {
    'bbox_inches': 'tight',
    'dpi': 150,
    'facecolor': 'white'
}
config.close_figures = True  # Close figures after display

# Create custom backend with configuration
backend = InlineBackend()
backend.config = config

# Create high-quality plot
plt.figure(figsize=(12, 8))
x = np.linspace(0, 20, 1000)
y1 = np.sin(x) * np.exp(-x/10)
y2 = np.cos(x) * np.exp(-x/10)

plt.plot(x, y1, 'b-', linewidth=2, label='Damped Sine', alpha=0.8)
plt.plot(x, y2, 'r-', linewidth=2, label='Damped Cosine', alpha=0.8)
plt.fill_between(x, y1, alpha=0.3, color='blue')
plt.fill_between(x, y2, alpha=0.3, color='red')

plt.xlabel('Time', fontsize=14)
plt.ylabel('Amplitude', fontsize=14)
plt.title('Damped Oscillations', fontsize=16, fontweight='bold')
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)

# Display with custom configuration
backend.show()

Subplot Management

from ipykernel.pylab.backend_inline import show
import matplotlib.pyplot as plt
import numpy as np

# Create subplot figure
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('Multiple Subplot Example', fontsize=16, fontweight='bold')

x = np.linspace(0, 10, 100)

# Subplot 1: Linear function
axes[0, 0].plot(x, x, 'b-', linewidth=2)
axes[0, 0].set_title('Linear: y = x')
axes[0, 0].grid(True)

# Subplot 2: Quadratic function
axes[0, 1].plot(x, x**2, 'r-', linewidth=2)
axes[0, 1].set_title('Quadratic: y = x²')
axes[0, 1].grid(True)

# Subplot 3: Exponential function
axes[1, 0].plot(x, np.exp(x/5), 'g-', linewidth=2)
axes[1, 0].set_title('Exponential: y = e^(x/5)')
axes[1, 0].grid(True)

# Subplot 4: Logarithmic function
x_log = np.linspace(0.1, 10, 100)
axes[1, 1].plot(x_log, np.log(x_log), 'm-', linewidth=2)
axes[1, 1].set_title('Logarithmic: y = ln(x)')
axes[1, 1].grid(True)

# Adjust layout and display
plt.tight_layout()
show()

Integration with IPython Display System

from ipykernel.pylab.backend_inline import show
from IPython.display import display, Image, SVG
import matplotlib.pyplot as plt
import numpy as np
import io
import base64

def create_plot_data():
    """Create sample plot data."""
    x = np.linspace(0, 2*np.pi, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    return x, y1, y2

def plot_to_base64(fig, format='png', dpi=100):
    """Convert matplotlib figure to base64 string."""
    buffer = io.BytesIO()
    fig.savefig(buffer, format=format, dpi=dpi, bbox_inches='tight')
    buffer.seek(0)
    image_data = buffer.getvalue()
    buffer.close()
    
    return base64.b64encode(image_data).decode()

# Create plot
x, y1, y2 = create_plot_data()

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, 'b-', linewidth=2, label='sin(x)')
ax.plot(x, y2, 'r--', linewidth=2, label='cos(x)')
ax.set_xlabel('Angle (radians)')
ax.set_ylabel('Value')
ax.set_title('Trigonometric Functions')
ax.legend()
ax.grid(True, alpha=0.3)

# Display using different methods
print("Method 1: Standard inline display")
show()

print("Method 2: Manual base64 encoding")
b64_data = plot_to_base64(fig)
display(Image(data=base64.b64decode(b64_data)))

plt.close(fig)  # Clean up

Error Handling and Cleanup

from ipykernel.pylab.backend_inline import show, flush_figures
import matplotlib.pyplot as plt
import numpy as np

def safe_plot_display():
    """Safely create and display plots with error handling."""
    try:
        # Create plot
        x = np.linspace(0, 10, 100)
        y = np.sin(x) / x  # This might cause division by zero
        
        plt.figure(figsize=(8, 6))
        plt.plot(x, y, 'b-', linewidth=2)
        plt.title('sinc(x) = sin(x)/x')
        plt.xlabel('x')
        plt.ylabel('sinc(x)')
        plt.grid(True)
        
        # Display plot
        show(close=True)  # Close after showing
        
        print("Plot displayed successfully")
        
    except Exception as e:
        print(f"Error creating plot: {e}")
        
        # Clean up any partial figures
        plt.close('all')
    
    finally:
        # Ensure all figures are flushed
        flush_figures()

# Run safe plotting
safe_plot_display()

# Verify no figures remain open
print(f"Open figures: {plt.get_fignums()}")

Install with Tessl CLI

npx tessl i tessl/pypi-ipykernel

docs

communication-framework.md

connection-management.md

core-kernel.md

data-utilities.md

gui-integration.md

in-process-kernels.md

index.md

io-streaming.md

kernel-application.md

kernel-embedding.md

matplotlib-integration.md

tile.json