Comprehensive Python library for creating static, animated, and interactive visualizations
—
Comprehensive color management, styling systems, and visual customization capabilities. Matplotlib provides extensive tools for color manipulation, custom colormaps, and global style configuration.
Functions for color format conversion and validation.
import matplotlib.colors as mcolors
def to_rgba(c, alpha=None) -> tuple:
"""Convert c to an RGBA color."""
def to_hex(c, keep_alpha=False) -> str:
"""Convert c to a hex color."""
def to_rgb(c) -> tuple:
"""Convert c to an RGB color."""
def is_color_like(c) -> bool:
"""Return whether c can be interpreted as an RGB(A) color."""
def to_rgba_array(c, alpha=None) -> np.ndarray:
"""Convert c to a numpy array of RGBA values."""
def rgb_to_hsv(rgb) -> tuple:
"""Convert float rgb values to hsv values."""
def hsv_to_rgb(hsv) -> tuple:
"""Convert hsv values to rgb values."""
def same_color(c1, c2) -> bool:
"""Return whether the two colors are the same within tolerance."""Classes for mapping data values to the [0, 1] range for colormap application.
class Normalize:
def __init__(self, vmin=None, vmax=None, clip=False):
"""Normalize data to [0, 1] range."""
def __call__(self, value, clip=None) -> np.ndarray:
"""Normalize value data in the [vmin, vmax] interval."""
def inverse(self, value) -> np.ndarray:
"""Inverse transformation from normalized [0, 1] to original range."""
class LogNorm(Normalize):
def __init__(self, vmin=None, vmax=None, clip=False):
"""Logarithmic normalization."""
class PowerNorm(Normalize):
def __init__(self, gamma, vmin=None, vmax=None, clip=False):
"""Power law normalization."""
class SymLogNorm(Normalize):
def __init__(self, linthresh, linscale=1.0, vmin=None, vmax=None, clip=False):
"""Symmetric logarithmic normalization."""
class BoundaryNorm(Normalize):
def __init__(self, boundaries, ncolors, clip=False, extend='neither'):
"""Generate a colormap index based on discrete intervals."""
class CenteredNorm(Normalize):
def __init__(self, vcenter=0, halfrange=None, vmin=None, vmax=None, clip=False):
"""Normalization centered on a specific value."""
class NoNorm(Normalize):
def __init__(self, vmin=None, vmax=None, clip=False):
"""Dummy replacement for Normalize for the case of no normalization."""
class FuncNorm(Normalize):
def __init__(self, functions, vmin=None, vmax=None, clip=False):
"""Arbitrary normalization using functions for forward and inverse."""Classes for creating and managing colormaps.
class Colormap:
def __init__(self, name, N=256):
"""Base class for all colormaps."""
def __call__(self, X, alpha=None, bytes=False) -> np.ndarray:
"""Apply colormap to data."""
def set_bad(self, color='k', alpha=None) -> None:
"""Set color for masked/invalid values."""
def set_under(self, color='k', alpha=None) -> None:
"""Set color for low out-of-range values."""
def set_over(self, color='k', alpha=None) -> None:
"""Set color for high out-of-range values."""
class LinearSegmentedColormap(Colormap):
def __init__(self, name, segmentdata, N=256, gamma=1.0):
"""Colormap from linear segments."""
@staticmethod
def from_list(name, colors, N=256, gamma=1.0) -> 'LinearSegmentedColormap':
"""Create colormap from a list of colors."""
class ListedColormap(Colormap):
def __init__(self, colors, name='from_list', N=None):
"""Colormap from a list of discrete colors."""Global colormap management and access.
# Global colormap registry
colormaps: ColormapRegistry
class ColormapRegistry:
def __getitem__(self, name) -> Colormap:
"""Get colormap by name."""
def __contains__(self, name) -> bool:
"""Check if colormap exists."""
def register(self, cmap, *, name=None, force=False) -> None:
"""Register a new colormap."""
def unregister(self, name) -> None:
"""Remove a colormap from the registry."""
def get_cmap(self, name=None, lut=None) -> Colormap:
"""Get a colormap instance."""
# Built-in colormaps
def get_cmap(name=None, lut=None) -> Colormap:
"""Get a colormap instance, optionally with number of colors."""Predefined color sequences for categorical data.
# Global color sequence registry
color_sequences: ColorSequenceRegistry
class ColorSequenceRegistry:
def __getitem__(self, name) -> list:
"""Get color sequence by name."""
def __contains__(self, name) -> bool:
"""Check if color sequence exists."""
def register(self, name, color_list) -> None:
"""Register a new color sequence."""Global configuration system for matplotlib appearance.
# Main configuration dictionary
rcParams: RcParams
class RcParams(dict):
"""Dictionary-like object for matplotlib configuration."""
def __setitem__(self, key, val) -> None:
"""Set parameter with validation."""
def __getitem__(self, key):
"""Get parameter value."""
def update(self, *args, **kwargs) -> None:
"""Update multiple parameters."""
# Configuration functions
def rc(group, **kwargs) -> None:
"""Set current rc params from kwargs."""
def rcdefaults() -> None:
"""Restore configuration to matplotlib defaults."""
def rc_context(rc=None, fname=None):
"""Context manager for temporarily changing rc parameters."""
def rc_params(fail_on_error=False) -> RcParams:
"""Return current rc parameters as a dictionary."""
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True) -> RcParams:
"""Return rc parameters from a file."""
# Default configurations
rcParamsDefault: RcParams # Default values
rcParamsOrig: RcParams # Original startup valuesPredefined style sheets and style context management.
import matplotlib.style as mplstyle
# Available styles
available: list # List of available style names
def use(style) -> None:
"""Use matplotlib style settings from a style specification."""
def context(style, after_reset=False):
"""Context manager for using style settings temporarily."""
def reload_library() -> None:
"""Reload the style library."""import matplotlib.colors as mcolors
# Convert colors between formats
rgba = mcolors.to_rgba('red') # (1.0, 0.0, 0.0, 1.0)
hex_color = mcolors.to_hex('blue') # '#0000FF'
rgb = mcolors.to_rgb('#FF5733') # (1.0, 0.34, 0.2)
# Validate colors
is_valid = mcolors.is_color_like('purple') # True
is_valid = mcolors.is_color_like('xyz') # False
# Convert arrays of colors
colors = ['red', 'green', 'blue', (1, 0, 1)]
rgba_array = mcolors.to_rgba_array(colors)
print(rgba_array.shape) # (4, 4) - 4 colors, 4 channels (RGBA)import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
# Create custom colormap from color list
colors = ['darkblue', 'blue', 'lightblue', 'white', 'lightcoral', 'red', 'darkred']
custom_cmap = mcolors.LinearSegmentedColormap.from_list('custom', colors, N=256)
# Register for later use
plt.colormaps.register(custom_cmap, name='my_colormap')
# Use the custom colormap
data = np.random.randn(20, 20)
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.imshow(data, cmap='viridis')
plt.title('Built-in Colormap')
plt.colorbar()
plt.subplot(1, 2, 2)
plt.imshow(data, cmap='my_colormap')
plt.title('Custom Colormap')
plt.colorbar()
plt.tight_layout()
plt.show()import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
# Generate sample data with large range
data = np.random.exponential(2, (20, 20)) * 1000
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Linear normalization (default)
im1 = axes[0, 0].imshow(data, cmap='viridis')
axes[0, 0].set_title('Linear Normalization')
plt.colorbar(im1, ax=axes[0, 0])
# Logarithmic normalization
norm_log = mcolors.LogNorm(vmin=data.min(), vmax=data.max())
im2 = axes[0, 1].imshow(data, cmap='viridis', norm=norm_log)
axes[0, 1].set_title('Log Normalization')
plt.colorbar(im2, ax=axes[0, 1])
# Power normalization
norm_power = mcolors.PowerNorm(gamma=0.5, vmin=data.min(), vmax=data.max())
im3 = axes[1, 0].imshow(data, cmap='viridis', norm=norm_power)
axes[1, 0].set_title('Power Normalization (γ=0.5)')
plt.colorbar(im3, ax=axes[1, 0])
# Centered normalization
norm_center = mcolors.CenteredNorm(vcenter=np.median(data))
im4 = axes[1, 1].imshow(data, cmap='RdBu_r', norm=norm_center)
axes[1, 1].set_title('Centered Normalization')
plt.colorbar(im4, ax=axes[1, 1])
plt.tight_layout()
plt.show()import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Save current settings
original_rcParams = mpl.rcParams.copy()
# Modify global settings
mpl.rc('figure', figsize=(12, 8), dpi=100)
mpl.rc('font', size=14, family='serif')
mpl.rc('axes', linewidth=2, titlesize=16, labelsize=14)
mpl.rc('lines', linewidth=3, markersize=8)
mpl.rc('grid', alpha=0.3, linewidth=1)
# Create plot with custom styling
x = np.linspace(0, 10, 50)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure()
plt.plot(x, y1, label='sin(x)', marker='o', markevery=5)
plt.plot(x, y2, label='cos(x)', marker='s', markevery=5)
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Styled Plot Example')
plt.legend()
plt.grid(True)
plt.show()
# Restore original settings
mpl.rcParams.update(original_rcParams)import matplotlib.pyplot as plt
import matplotlib.style as mplstyle
import numpy as np
# List available styles
print("Available styles:", mplstyle.available[:5]) # Show first 5
# Use different styles
styles = ['default', 'seaborn-v0_8', 'ggplot', 'bmh']
data = np.random.randn(1000)
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
for ax, style in zip(axes.flat, styles):
with mplstyle.context(style):
ax.hist(data, bins=30, alpha=0.7, edgecolor='black')
ax.set_title(f'Style: {style}')
ax.grid(True)
plt.tight_layout()
plt.show()
# Combine multiple styles
with mplstyle.context(['seaborn-v0_8', 'seaborn-v0_8-darkgrid']):
plt.figure(figsize=(10, 6))
plt.plot(np.random.randn(100).cumsum(), linewidth=2)
plt.title('Combined Styles')
plt.show()import matplotlib.pyplot as plt
import numpy as np
# Use built-in color sequences
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
# Get color sequence
colors = plt.colormaps['tab10'](np.linspace(0, 1, len(categories)))
plt.figure(figsize=(12, 5))
# Bar chart with color sequence
plt.subplot(1, 2, 1)
bars = plt.bar(categories, values, color=colors)
plt.title('Tab10 Color Sequence')
plt.ylabel('Values')
# Pie chart with same colors
plt.subplot(1, 2, 2)
plt.pie(values, labels=categories, colors=colors, autopct='%1.1f%%')
plt.title('Matching Colors')
plt.tight_layout()
plt.show()Install with Tessl CLI
npx tessl i tessl/pypi-matplotlib