0
# Color and Styling
1
2
Comprehensive color management, styling systems, and visual customization capabilities. Matplotlib provides extensive tools for color manipulation, custom colormaps, and global style configuration.
3
4
## Capabilities
5
6
### Color Conversion and Utilities
7
8
Functions for color format conversion and validation.
9
10
```python { .api }
11
import matplotlib.colors as mcolors
12
13
def to_rgba(c, alpha=None) -> tuple:
14
"""Convert c to an RGBA color."""
15
16
def to_hex(c, keep_alpha=False) -> str:
17
"""Convert c to a hex color."""
18
19
def to_rgb(c) -> tuple:
20
"""Convert c to an RGB color."""
21
22
def is_color_like(c) -> bool:
23
"""Return whether c can be interpreted as an RGB(A) color."""
24
25
def to_rgba_array(c, alpha=None) -> np.ndarray:
26
"""Convert c to a numpy array of RGBA values."""
27
28
def rgb_to_hsv(rgb) -> tuple:
29
"""Convert float rgb values to hsv values."""
30
31
def hsv_to_rgb(hsv) -> tuple:
32
"""Convert hsv values to rgb values."""
33
34
def same_color(c1, c2) -> bool:
35
"""Return whether the two colors are the same within tolerance."""
36
```
37
38
### Normalization Classes
39
40
Classes for mapping data values to the [0, 1] range for colormap application.
41
42
```python { .api }
43
class Normalize:
44
def __init__(self, vmin=None, vmax=None, clip=False):
45
"""Normalize data to [0, 1] range."""
46
47
def __call__(self, value, clip=None) -> np.ndarray:
48
"""Normalize value data in the [vmin, vmax] interval."""
49
50
def inverse(self, value) -> np.ndarray:
51
"""Inverse transformation from normalized [0, 1] to original range."""
52
53
class LogNorm(Normalize):
54
def __init__(self, vmin=None, vmax=None, clip=False):
55
"""Logarithmic normalization."""
56
57
class PowerNorm(Normalize):
58
def __init__(self, gamma, vmin=None, vmax=None, clip=False):
59
"""Power law normalization."""
60
61
class SymLogNorm(Normalize):
62
def __init__(self, linthresh, linscale=1.0, vmin=None, vmax=None, clip=False):
63
"""Symmetric logarithmic normalization."""
64
65
class BoundaryNorm(Normalize):
66
def __init__(self, boundaries, ncolors, clip=False, extend='neither'):
67
"""Generate a colormap index based on discrete intervals."""
68
69
class CenteredNorm(Normalize):
70
def __init__(self, vcenter=0, halfrange=None, vmin=None, vmax=None, clip=False):
71
"""Normalization centered on a specific value."""
72
73
class NoNorm(Normalize):
74
def __init__(self, vmin=None, vmax=None, clip=False):
75
"""Dummy replacement for Normalize for the case of no normalization."""
76
77
class FuncNorm(Normalize):
78
def __init__(self, functions, vmin=None, vmax=None, clip=False):
79
"""Arbitrary normalization using functions for forward and inverse."""
80
```
81
82
### Colormap Classes
83
84
Classes for creating and managing colormaps.
85
86
```python { .api }
87
class Colormap:
88
def __init__(self, name, N=256):
89
"""Base class for all colormaps."""
90
91
def __call__(self, X, alpha=None, bytes=False) -> np.ndarray:
92
"""Apply colormap to data."""
93
94
def set_bad(self, color='k', alpha=None) -> None:
95
"""Set color for masked/invalid values."""
96
97
def set_under(self, color='k', alpha=None) -> None:
98
"""Set color for low out-of-range values."""
99
100
def set_over(self, color='k', alpha=None) -> None:
101
"""Set color for high out-of-range values."""
102
103
class LinearSegmentedColormap(Colormap):
104
def __init__(self, name, segmentdata, N=256, gamma=1.0):
105
"""Colormap from linear segments."""
106
107
@staticmethod
108
def from_list(name, colors, N=256, gamma=1.0) -> 'LinearSegmentedColormap':
109
"""Create colormap from a list of colors."""
110
111
class ListedColormap(Colormap):
112
def __init__(self, colors, name='from_list', N=None):
113
"""Colormap from a list of discrete colors."""
114
```
115
116
### Colormap Registry and Access
117
118
Global colormap management and access.
119
120
```python { .api }
121
# Global colormap registry
122
colormaps: ColormapRegistry
123
124
class ColormapRegistry:
125
def __getitem__(self, name) -> Colormap:
126
"""Get colormap by name."""
127
128
def __contains__(self, name) -> bool:
129
"""Check if colormap exists."""
130
131
def register(self, cmap, *, name=None, force=False) -> None:
132
"""Register a new colormap."""
133
134
def unregister(self, name) -> None:
135
"""Remove a colormap from the registry."""
136
137
def get_cmap(self, name=None, lut=None) -> Colormap:
138
"""Get a colormap instance."""
139
140
# Built-in colormaps
141
def get_cmap(name=None, lut=None) -> Colormap:
142
"""Get a colormap instance, optionally with number of colors."""
143
```
144
145
### Color Sequences
146
147
Predefined color sequences for categorical data.
148
149
```python { .api }
150
# Global color sequence registry
151
color_sequences: ColorSequenceRegistry
152
153
class ColorSequenceRegistry:
154
def __getitem__(self, name) -> list:
155
"""Get color sequence by name."""
156
157
def __contains__(self, name) -> bool:
158
"""Check if color sequence exists."""
159
160
def register(self, name, color_list) -> None:
161
"""Register a new color sequence."""
162
```
163
164
### RC Parameters and Configuration
165
166
Global configuration system for matplotlib appearance.
167
168
```python { .api }
169
# Main configuration dictionary
170
rcParams: RcParams
171
172
class RcParams(dict):
173
"""Dictionary-like object for matplotlib configuration."""
174
175
def __setitem__(self, key, val) -> None:
176
"""Set parameter with validation."""
177
178
def __getitem__(self, key):
179
"""Get parameter value."""
180
181
def update(self, *args, **kwargs) -> None:
182
"""Update multiple parameters."""
183
184
# Configuration functions
185
def rc(group, **kwargs) -> None:
186
"""Set current rc params from kwargs."""
187
188
def rcdefaults() -> None:
189
"""Restore configuration to matplotlib defaults."""
190
191
def rc_context(rc=None, fname=None):
192
"""Context manager for temporarily changing rc parameters."""
193
194
def rc_params(fail_on_error=False) -> RcParams:
195
"""Return current rc parameters as a dictionary."""
196
197
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True) -> RcParams:
198
"""Return rc parameters from a file."""
199
200
# Default configurations
201
rcParamsDefault: RcParams # Default values
202
rcParamsOrig: RcParams # Original startup values
203
```
204
205
### Style System
206
207
Predefined style sheets and style context management.
208
209
```python { .api }
210
import matplotlib.style as mplstyle
211
212
# Available styles
213
available: list # List of available style names
214
215
def use(style) -> None:
216
"""Use matplotlib style settings from a style specification."""
217
218
def context(style, after_reset=False):
219
"""Context manager for using style settings temporarily."""
220
221
def reload_library() -> None:
222
"""Reload the style library."""
223
```
224
225
## Usage Examples
226
227
### Color Conversion
228
229
```python
230
import matplotlib.colors as mcolors
231
232
# Convert colors between formats
233
rgba = mcolors.to_rgba('red') # (1.0, 0.0, 0.0, 1.0)
234
hex_color = mcolors.to_hex('blue') # '#0000FF'
235
rgb = mcolors.to_rgb('#FF5733') # (1.0, 0.34, 0.2)
236
237
# Validate colors
238
is_valid = mcolors.is_color_like('purple') # True
239
is_valid = mcolors.is_color_like('xyz') # False
240
241
# Convert arrays of colors
242
colors = ['red', 'green', 'blue', (1, 0, 1)]
243
rgba_array = mcolors.to_rgba_array(colors)
244
print(rgba_array.shape) # (4, 4) - 4 colors, 4 channels (RGBA)
245
```
246
247
### Custom Colormaps
248
249
```python
250
import matplotlib.pyplot as plt
251
import matplotlib.colors as mcolors
252
import numpy as np
253
254
# Create custom colormap from color list
255
colors = ['darkblue', 'blue', 'lightblue', 'white', 'lightcoral', 'red', 'darkred']
256
custom_cmap = mcolors.LinearSegmentedColormap.from_list('custom', colors, N=256)
257
258
# Register for later use
259
plt.colormaps.register(custom_cmap, name='my_colormap')
260
261
# Use the custom colormap
262
data = np.random.randn(20, 20)
263
plt.figure(figsize=(10, 4))
264
265
plt.subplot(1, 2, 1)
266
plt.imshow(data, cmap='viridis')
267
plt.title('Built-in Colormap')
268
plt.colorbar()
269
270
plt.subplot(1, 2, 2)
271
plt.imshow(data, cmap='my_colormap')
272
plt.title('Custom Colormap')
273
plt.colorbar()
274
275
plt.tight_layout()
276
plt.show()
277
```
278
279
### Data Normalization
280
281
```python
282
import matplotlib.pyplot as plt
283
import matplotlib.colors as mcolors
284
import numpy as np
285
286
# Generate sample data with large range
287
data = np.random.exponential(2, (20, 20)) * 1000
288
289
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
290
291
# Linear normalization (default)
292
im1 = axes[0, 0].imshow(data, cmap='viridis')
293
axes[0, 0].set_title('Linear Normalization')
294
plt.colorbar(im1, ax=axes[0, 0])
295
296
# Logarithmic normalization
297
norm_log = mcolors.LogNorm(vmin=data.min(), vmax=data.max())
298
im2 = axes[0, 1].imshow(data, cmap='viridis', norm=norm_log)
299
axes[0, 1].set_title('Log Normalization')
300
plt.colorbar(im2, ax=axes[0, 1])
301
302
# Power normalization
303
norm_power = mcolors.PowerNorm(gamma=0.5, vmin=data.min(), vmax=data.max())
304
im3 = axes[1, 0].imshow(data, cmap='viridis', norm=norm_power)
305
axes[1, 0].set_title('Power Normalization (γ=0.5)')
306
plt.colorbar(im3, ax=axes[1, 0])
307
308
# Centered normalization
309
norm_center = mcolors.CenteredNorm(vcenter=np.median(data))
310
im4 = axes[1, 1].imshow(data, cmap='RdBu_r', norm=norm_center)
311
axes[1, 1].set_title('Centered Normalization')
312
plt.colorbar(im4, ax=axes[1, 1])
313
314
plt.tight_layout()
315
plt.show()
316
```
317
318
### Global Style Configuration
319
320
```python
321
import matplotlib.pyplot as plt
322
import matplotlib as mpl
323
import numpy as np
324
325
# Save current settings
326
original_rcParams = mpl.rcParams.copy()
327
328
# Modify global settings
329
mpl.rc('figure', figsize=(12, 8), dpi=100)
330
mpl.rc('font', size=14, family='serif')
331
mpl.rc('axes', linewidth=2, titlesize=16, labelsize=14)
332
mpl.rc('lines', linewidth=3, markersize=8)
333
mpl.rc('grid', alpha=0.3, linewidth=1)
334
335
# Create plot with custom styling
336
x = np.linspace(0, 10, 50)
337
y1 = np.sin(x)
338
y2 = np.cos(x)
339
340
plt.figure()
341
plt.plot(x, y1, label='sin(x)', marker='o', markevery=5)
342
plt.plot(x, y2, label='cos(x)', marker='s', markevery=5)
343
plt.xlabel('X values')
344
plt.ylabel('Y values')
345
plt.title('Styled Plot Example')
346
plt.legend()
347
plt.grid(True)
348
plt.show()
349
350
# Restore original settings
351
mpl.rcParams.update(original_rcParams)
352
```
353
354
### Style Sheets
355
356
```python
357
import matplotlib.pyplot as plt
358
import matplotlib.style as mplstyle
359
import numpy as np
360
361
# List available styles
362
print("Available styles:", mplstyle.available[:5]) # Show first 5
363
364
# Use different styles
365
styles = ['default', 'seaborn-v0_8', 'ggplot', 'bmh']
366
data = np.random.randn(1000)
367
368
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
369
370
for ax, style in zip(axes.flat, styles):
371
with mplstyle.context(style):
372
ax.hist(data, bins=30, alpha=0.7, edgecolor='black')
373
ax.set_title(f'Style: {style}')
374
ax.grid(True)
375
376
plt.tight_layout()
377
plt.show()
378
379
# Combine multiple styles
380
with mplstyle.context(['seaborn-v0_8', 'seaborn-v0_8-darkgrid']):
381
plt.figure(figsize=(10, 6))
382
plt.plot(np.random.randn(100).cumsum(), linewidth=2)
383
plt.title('Combined Styles')
384
plt.show()
385
```
386
387
### Color Sequences for Categorical Data
388
389
```python
390
import matplotlib.pyplot as plt
391
import numpy as np
392
393
# Use built-in color sequences
394
categories = ['A', 'B', 'C', 'D', 'E']
395
values = [23, 45, 56, 78, 32]
396
397
# Get color sequence
398
colors = plt.colormaps['tab10'](np.linspace(0, 1, len(categories)))
399
400
plt.figure(figsize=(12, 5))
401
402
# Bar chart with color sequence
403
plt.subplot(1, 2, 1)
404
bars = plt.bar(categories, values, color=colors)
405
plt.title('Tab10 Color Sequence')
406
plt.ylabel('Values')
407
408
# Pie chart with same colors
409
plt.subplot(1, 2, 2)
410
plt.pie(values, labels=categories, colors=colors, autopct='%1.1f%%')
411
plt.title('Matching Colors')
412
413
plt.tight_layout()
414
plt.show()
415
```