Comprehensive Python library for creating static, animated, and interactive visualizations
—
Output format control and GUI integration. Matplotlib provides multiple backend implementations for different platforms, display systems, and file formats, enabling flexible deployment across environments.
Functions for selecting and controlling matplotlib backends.
import matplotlib
import matplotlib.pyplot as plt
# Core matplotlib backend functions
def use(backend, *, force=True) -> None:
"""Select the backend used for rendering and GUI integration."""
def get_backend() -> str:
"""Return the name of the current backend."""
def interactive(b=None) -> bool:
"""Set or query interactive mode."""
def is_interactive() -> bool:
"""Return whether plots are updated after every plotting command."""
# Pyplot backend and interaction functions
def switch_backend(newbackend) -> None:
"""Switch the default backend."""
def show(*args, **kwargs) -> None:
"""Display all figures and enter the GUI event loop if needed."""
def ion() -> None:
"""Turn on interactive mode."""
def ioff() -> None:
"""Turn off interactive mode."""GUI backends for interactive plotting and user interaction.
# Qt-based backends
'Qt5Agg' # Qt5 with Anti-Grain Geometry (AGG) rendering
'Qt5Cairo' # Qt5 with Cairo rendering
# Tkinter backend
'TkAgg' # Tk with AGG rendering
'TkCairo' # Tk with Cairo rendering
# GTK backends
'GTK3Agg' # GTK3 with AGG rendering
'GTK3Cairo' # GTK3 with Cairo rendering
# Platform-specific backends
'MacOSX' # Native macOS Cocoa backend
'WX' # wxPython backend
'WXAgg' # wxPython with AGG rendering
# Web-based backend
'WebAgg' # Web browser-based interactive backend
'notebook' # Jupyter notebook integration
'nbagg' # Jupyter notebook with interactivityFile output backends for saving plots without GUI interaction.
# Raster formats
'Agg' # Anti-Grain Geometry (PNG, RGBA)
'Cairo' # Cairo graphics (PNG, PDF, PS, SVG)
# Vector formats
'PDF' # Portable Document Format
'PS' # PostScript
'SVG' # Scalable Vector Graphics
# Additional formats
'PGF' # PGF/TikZ for LaTeX
'Template' # Template backend for custom outputFunctions for saving plots to various file formats.
def savefig(fname, *, dpi='figure', format=None, metadata=None,
bbox_inches=None, pad_inches=0.1, facecolor='auto',
edgecolor='auto', backend=None, **kwargs) -> None:
"""Save the current figure to a file."""
# Figure.savefig method
class Figure:
def savefig(self, fname, *, transparent=None, dpi='figure', format=None,
metadata=None, bbox_inches=None, pad_inches=0.1,
facecolor='auto', edgecolor='auto', backend=None,
**kwargs) -> None:
"""Save the figure to a file."""Base classes for implementing custom backends.
from matplotlib.backends.backend_bases import *
class FigureCanvasBase:
"""Abstract base class for figure canvas implementations."""
def draw(self) -> None:
"""Draw the figure."""
def draw_idle(self) -> None:
"""Request a draw when the GUI is idle."""
def print_figure(self, filename, **kwargs) -> None:
"""Print/save the figure to a file."""
def mpl_connect(self, s, func) -> int:
"""Connect a callback function to a matplotlib event."""
def mpl_disconnect(self, cid) -> None:
"""Disconnect a callback by connection id."""
class RendererBase:
"""Abstract base class for renderers."""
def draw_path(self, gc, path, transform, rgbFace=None) -> None:
"""Draw a path using the graphics context."""
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None) -> None:
"""Draw text at position (x, y)."""
def draw_image(self, gc, x, y, im, transform=None) -> None:
"""Draw an image at position (x, y)."""
class FigureManagerBase:
"""Abstract base class for figure window managers."""
def show(self) -> None:
"""Show the figure window."""
def destroy(self) -> None:
"""Destroy the figure window."""
def set_window_title(self, title) -> None:
"""Set the title of the figure window."""Options and metadata for different output formats.
# PNG format options
PNG_OPTIONS = {
'dpi': 'figure', # Resolution in dots per inch
'facecolor': 'auto', # Figure background color
'edgecolor': 'auto', # Figure edge color
'transparent': False, # Transparent background
'bbox_inches': None, # Bounding box (tight, or None)
'pad_inches': 0.1, # Padding around saved area
'metadata': None # PNG metadata dictionary
}
# PDF format options
PDF_OPTIONS = {
'dpi': 'figure',
'facecolor': 'auto',
'edgecolor': 'auto',
'bbox_inches': None,
'pad_inches': 0.1,
'metadata': None, # PDF metadata dictionary
'backend_pdf': None # Backend-specific options
}
# SVG format options
SVG_OPTIONS = {
'dpi': 'figure',
'facecolor': 'auto',
'edgecolor': 'auto',
'bbox_inches': None,
'pad_inches': 0.1,
'metadata': None, # SVG metadata
'svg.image_inline': True, # Embed images inline
'svg.fonttype': 'path' # How to handle fonts
}
# PostScript options
PS_OPTIONS = {
'dpi': 'figure',
'facecolor': 'auto',
'edgecolor': 'auto',
'bbox_inches': None,
'pad_inches': 0.1,
'papertype': 'auto', # Paper size
'orientation': 'portrait' # Page orientation
}import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Check current backend
print(f"Current backend: {matplotlib.get_backend()}")
# List available backends
print(f"Available interactive backends: {matplotlib.backend_bases.Backend}")
# Set specific backend (must be done before importing pyplot)
# matplotlib.use('TkAgg') # For Tkinter GUI
# matplotlib.use('Qt5Agg') # For Qt5 GUI
# matplotlib.use('Agg') # For non-interactive (file output only)
# 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)
plt.title(f'Plot using {matplotlib.get_backend()} backend')
plt.xlabel('X')
plt.ylabel('sin(X)')
plt.grid(True)
plt.show()import matplotlib.pyplot as plt
import numpy as np
# Create sample plot
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
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('X')
ax.set_ylabel('Y')
ax.set_title('Trigonometric Functions')
ax.legend()
ax.grid(True)
# Save in different formats
formats = {
'PNG': {'format': 'png', 'dpi': 300, 'bbox_inches': 'tight'},
'PDF': {'format': 'pdf', 'bbox_inches': 'tight'},
'SVG': {'format': 'svg', 'bbox_inches': 'tight'},
'EPS': {'format': 'eps', 'bbox_inches': 'tight'},
'JPG': {'format': 'jpg', 'dpi': 150, 'bbox_inches': 'tight'}
}
for name, options in formats.items():
filename = f'trigonometric_plot.{options["format"]}'
try:
fig.savefig(filename, **options)
print(f"Saved as {filename}")
except Exception as e:
print(f"Could not save as {name}: {e}")
plt.show()import matplotlib.pyplot as plt
import numpy as np
# Set up for publication-quality output
plt.rcParams.update({
'font.size': 12,
'font.family': 'serif',
'text.usetex': False, # Set True if LaTeX is available
'figure.figsize': (8, 6),
'figure.dpi': 100,
'savefig.dpi': 300,
'savefig.format': 'pdf',
'savefig.bbox': 'tight',
'axes.linewidth': 1.2,
'axes.spines.top': False,
'axes.spines.right': False,
'xtick.major.size': 4,
'ytick.major.size': 4,
'legend.frameon': False
})
# Create publication-quality plot
x = np.linspace(0, 2*np.pi, 1000)
y1 = np.sin(x)
y2 = np.sin(2*x) * 0.5
y3 = np.sin(3*x) * 0.25
fig, ax = plt.subplots()
ax.plot(x, y1, 'k-', linewidth=1.5, label='$\\sin(x)$')
ax.plot(x, y2, 'k--', linewidth=1.5, label='$0.5\\sin(2x)$')
ax.plot(x, y3, 'k:', linewidth=1.5, label='$0.25\\sin(3x)$')
ax.set_xlabel('$x$ (radians)')
ax.set_ylabel('Amplitude')
ax.set_title('Harmonic Functions')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3, linewidth=0.5)
# Set custom axis limits and ticks
ax.set_xlim(0, 2*np.pi)
ax.set_xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
ax.set_xticklabels(['0', '$\\pi/2$', '$\\pi$', '$3\\pi/2$', '$2\\pi$'])
# Save with high quality settings
fig.savefig('publication_plot.pdf', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
fig.savefig('publication_plot.png', dpi=600, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.show()import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def create_interactive_plot():
"""Create plot with interactive features."""
fig, ax = plt.subplots(figsize=(10, 6))
x = np.linspace(0, 10, 100)
y = np.sin(x)
line, = ax.plot(x, y, 'b-', linewidth=2)
ax.set_xlabel('X')
ax.set_ylabel('sin(X)')
ax.set_title(f'Interactive Plot - Backend: {matplotlib.get_backend()}')
ax.grid(True)
# Add interactive callback
def on_click(event):
if event.inaxes == ax:
print(f"Clicked at ({event.xdata:.2f}, {event.ydata:.2f})")
fig.canvas.mpl_connect('button_press_event', on_click)
return fig, ax
# Test different interactive backends
interactive_backends = ['Qt5Agg', 'TkAgg', 'MacOSX']
for backend in interactive_backends:
try:
# Note: In practice, backend should be set before importing pyplot
print(f"\\nTesting backend: {backend}")
# This would normally require restarting Python
# matplotlib.use(backend)
fig, ax = create_interactive_plot()
plt.show(block=False) # Non-blocking show
# Backend-specific features
if 'Qt' in matplotlib.get_backend():
print("Qt backend: Supports native zoom, pan, configure subplots")
elif 'Tk' in matplotlib.get_backend():
print("Tk backend: Lightweight, good for simple interactions")
elif 'MacOSX' in matplotlib.get_backend():
print("macOS backend: Native macOS integration")
except Exception as e:
print(f"Backend {backend} not available: {e}")
plt.show()import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Use WebAgg for web-based interaction
# matplotlib.use('WebAgg')
# Create interactive web plot
fig, ax = plt.subplots(figsize=(10, 6))
# Generate data
t = np.linspace(0, 4*np.pi, 200)
x = np.sin(t)
y = np.cos(t * 1.5)
ax.plot(t, x, 'b-', linewidth=2, label='sin(t)', alpha=0.8)
ax.plot(t, y, 'r-', linewidth=2, label='cos(1.5t)', alpha=0.8)
ax.set_xlabel('Time')
ax.set_ylabel('Amplitude')
ax.set_title('Interactive Web Plot')
ax.legend()
ax.grid(True, alpha=0.3)
# The WebAgg backend automatically creates a web server
# and opens the plot in a browser with zoom/pan controls
print("WebAgg backend creates interactive web interface")
print("Navigate to http://127.0.0.1:8988 to view the plot")
plt.show()import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
# Create plot with comprehensive metadata
fig, ax = plt.subplots(figsize=(10, 6))
x = np.linspace(0, 10, 100)
y = np.exp(-x/5) * np.sin(x)
ax.plot(x, y, 'b-', linewidth=2)
ax.set_xlabel('Distance (m)')
ax.set_ylabel('Amplitude')
ax.set_title('Exponentially Decaying Oscillation')
ax.grid(True, alpha=0.3)
# Comprehensive metadata
metadata_common = {
'Title': 'Exponentially Decaying Oscillation',
'Author': 'Scientific Computing Lab',
'Subject': 'Mathematical Visualization',
'Keywords': 'exponential decay, oscillation, mathematics',
'Creator': 'matplotlib',
'CreationDate': datetime.now(),
'Description': 'Plot showing exponential decay with oscillation'
}
# Format-specific exports with metadata
export_configs = {
'high_res_png': {
'filename': 'decay_oscillation_highres.png',
'format': 'png',
'dpi': 600,
'bbox_inches': 'tight',
'facecolor': 'white',
'edgecolor': 'none',
'metadata': metadata_common
},
'web_png': {
'filename': 'decay_oscillation_web.png',
'format': 'png',
'dpi': 150,
'bbox_inches': 'tight',
'facecolor': 'white',
'metadata': metadata_common
},
'vector_pdf': {
'filename': 'decay_oscillation_vector.pdf',
'format': 'pdf',
'bbox_inches': 'tight',
'metadata': metadata_common
},
'scalable_svg': {
'filename': 'decay_oscillation_scalable.svg',
'format': 'svg',
'bbox_inches': 'tight',
'metadata': metadata_common
}
}
# Export in all configured formats
for config_name, options in export_configs.items():
try:
fig.savefig(**options)
print(f"Exported {config_name}: {options['filename']}")
except Exception as e:
print(f"Failed to export {config_name}: {e}")
plt.show()
# Print file size comparison
import os
print("\\nFile size comparison:")
for config_name, options in export_configs.items():
filename = options['filename']
if os.path.exists(filename):
size_kb = os.path.getsize(filename) / 1024
print(f"{filename}: {size_kb:.1f} KB")Install with Tessl CLI
npx tessl i tessl/pypi-matplotlib