0
# Colors and Colormaps
1
2
Advanced color handling system with perceptual color spaces, flexible colormap creation, enhanced color cycles, and seamless integration with matplotlib's color infrastructure. Proplot provides a comprehensive color system that extends matplotlib's capabilities with perceptual color spaces, enhanced colormap creation, and intelligent color management.
3
4
## Capabilities
5
6
### Colormap Classes
7
8
Enhanced colormap classes providing superior color handling with perceptual uniformity and flexible customization options.
9
10
```python { .api }
11
class DiscreteColormap:
12
"""
13
Replacement for matplotlib's ListedColormap with enhanced features.
14
15
Enhanced discrete colormap with:
16
- Perceptual color space support
17
- Automatic color interpolation
18
- Flexible color specification
19
- Seamless matplotlib integration
20
"""
21
22
def __init__(self, colors, name=None, **kwargs):
23
"""
24
Create discrete colormap from color list.
25
26
Parameters:
27
- colors (sequence): List of color specifications
28
- name (str): Colormap name for registration
29
- **kwargs: Additional colormap parameters
30
"""
31
32
class ContinuousColormap:
33
"""
34
Replacement for matplotlib's LinearSegmentedColormap.
35
36
Enhanced continuous colormap with:
37
- Smooth color transitions
38
- Multiple interpolation methods
39
- Perceptual color space support
40
- Advanced segmentation control
41
"""
42
43
def __init__(self, colors, name=None, **kwargs):
44
"""
45
Create continuous colormap from color specifications.
46
47
Parameters:
48
- colors (sequence): Color specifications for interpolation
49
- name (str): Colormap name for registration
50
- **kwargs: Additional interpolation parameters
51
"""
52
53
class PerceptualColormap:
54
"""
55
Colormap with linear transitions across hue, saturation, luminance.
56
57
Perceptually uniform colormap providing:
58
- Linear transitions in perceptual color spaces
59
- Hue, saturation, and luminance control
60
- Automatic color space optimization
61
- Superior visual uniformity
62
"""
63
64
def __init__(self, colors, space='hcl', **kwargs):
65
"""
66
Create perceptually uniform colormap.
67
68
Parameters:
69
- colors (sequence): Color specifications for transitions
70
- space (str): Perceptual color space ('hcl', 'hsl', 'hsv')
71
- **kwargs: Color space and interpolation parameters
72
"""
73
```
74
75
### Normalization Classes
76
77
Advanced normalization classes for flexible data-to-color mapping with support for discrete levels, diverging data, and segmented scaling.
78
79
```python { .api }
80
class DiscreteNorm:
81
"""
82
Meta-normalizer that discretizes continuous normalizers.
83
84
Provides discrete color mapping with:
85
- Flexible level specification
86
- Automatic level generation
87
- Integration with continuous normalizers
88
- Enhanced categorical visualization
89
"""
90
91
def __init__(self, levels, norm=None, **kwargs):
92
"""
93
Create discrete normalization.
94
95
Parameters:
96
- levels (int/array): Number of levels or explicit level values
97
- norm (Normalize): Base normalizer to discretize
98
- **kwargs: Additional normalization parameters
99
"""
100
101
class DivergingNorm:
102
"""
103
Normalizer ensuring central data value lies at central colormap color.
104
105
Diverging normalization with:
106
- Automatic center detection
107
- Symmetric scaling around center
108
- Enhanced diverging colormap integration
109
- Flexible center value specification
110
"""
111
112
def __init__(self, vcenter=0, vmin=None, vmax=None):
113
"""
114
Create diverging normalization.
115
116
Parameters:
117
- vcenter (float): Central value for colormap center
118
- vmin (float): Minimum data value
119
- vmax (float): Maximum data value
120
"""
121
122
class SegmentedNorm:
123
"""
124
Normalizer that scales data linearly with respect to level sequence.
125
126
Segmented normalization providing:
127
- Non-uniform level spacing
128
- Linear scaling within segments
129
- Flexible breakpoint specification
130
- Enhanced contour plot integration
131
"""
132
133
def __init__(self, levels, **kwargs):
134
"""
135
Create segmented normalization.
136
137
Parameters:
138
- levels (array): Level boundaries for segmentation
139
- **kwargs: Additional segmentation parameters
140
"""
141
```
142
143
### Constructor Functions
144
145
Flexible factory functions for creating colormaps, normalizers, and color cycles from various input specifications.
146
147
```python { .api }
148
def Colormap(*args, **kwargs):
149
"""
150
Construct colormap instances from various inputs.
151
152
Parameters:
153
- *args: Colormap specifications (names, files, colors, arrays)
154
- space (str): Color space for interpolation ('rgb', 'hcl', 'hsl')
155
- discrete (bool): Create discrete vs. continuous colormap
156
- cyclic (bool): Create cyclic colormap
157
- **kwargs: Additional colormap creation parameters
158
159
Input Types:
160
- Colormap names: 'viridis', 'plasma', 'Blues'
161
- Color lists: ['red', 'blue', 'green']
162
- Color arrays: numpy arrays of RGB values
163
- File paths: .json, .hex, .rgb colormap files
164
- matplotlib colormaps: Existing colormap objects
165
166
Returns:
167
Colormap: DiscreteColormap or ContinuousColormap instance
168
"""
169
170
def Norm(*args, **kwargs):
171
"""
172
Construct normalizer instances from specifications.
173
174
Parameters:
175
- *args: Normalization specifications
176
- levels (int/array): Discrete levels for discretization
177
- vcenter (float): Center value for diverging normalization
178
- **kwargs: Additional normalization parameters
179
180
Normalization Types:
181
- 'linear': Linear normalization
182
- 'log': Logarithmic normalization
183
- 'symlog': Symmetric logarithmic normalization
184
- 'discrete': Discrete level normalization
185
- 'diverging': Diverging (centered) normalization
186
- 'segmented': Segmented level normalization
187
188
Returns:
189
Normalize: Appropriate normalization instance
190
"""
191
192
def Cycle(*args, **kwargs):
193
"""
194
Construct color cycle instances from various inputs.
195
196
Parameters:
197
- *args: Color cycle specifications (names, colors, files)
198
- samples (int): Number of colors to sample from continuous source
199
- **kwargs: Additional cycle creation parameters
200
201
Input Types:
202
- Cycle names: 'colorblind', 'tab10', 'Set1'
203
- Color lists: ['red', 'blue', 'green']
204
- Colormap sampling: ('viridis', 5) for 5 colors from viridis
205
- File paths: .hex, .rgb color cycle files
206
207
Returns:
208
DiscreteColormap: Color cycle as discrete colormap
209
"""
210
```
211
212
### Color Utility Functions
213
214
Comprehensive collection of color manipulation functions for converting between color spaces, adjusting color properties, and working with color specifications.
215
216
```python { .api }
217
def get_colors(*args, **kwargs):
218
"""
219
Get colors from registered or on-the-fly color cycle.
220
221
Parameters:
222
- *args: Color cycle specification
223
- samples (int): Number of colors to retrieve
224
- **kwargs: Additional color retrieval parameters
225
226
Returns:
227
list: List of color specifications
228
"""
229
230
def set_hue(color, hue, space='hcl'):
231
"""
232
Return color with different hue channel value.
233
234
Parameters:
235
- color (color-spec): Input color specification
236
- hue (float): New hue value (0-360 for hcl/hsl)
237
- space (str): Color space for hue adjustment
238
239
Returns:
240
str: Color specification with modified hue
241
"""
242
243
def set_saturation(color, saturation, space='hcl'):
244
"""
245
Return color with different saturation channel value.
246
247
Parameters:
248
- color (color-spec): Input color specification
249
- saturation (float): New saturation value (0-100 for hcl/hsl)
250
- space (str): Color space for saturation adjustment
251
252
Returns:
253
str: Color specification with modified saturation
254
"""
255
256
def set_luminance(color, luminance, space='hcl'):
257
"""
258
Return color with different luminance channel value.
259
260
Parameters:
261
- color (color-spec): Input color specification
262
- luminance (float): New luminance value (0-100 for hcl/hsl)
263
- space (str): Color space for luminance adjustment
264
265
Returns:
266
str: Color specification with modified luminance
267
"""
268
269
def set_alpha(color, alpha):
270
"""
271
Return color with specified opacity channel value.
272
273
Parameters:
274
- color (color-spec): Input color specification
275
- alpha (float): Opacity value (0-1, 0=transparent, 1=opaque)
276
277
Returns:
278
str: Color specification with modified alpha channel
279
"""
280
281
def shift_hue(color, shift=0, space='hcl'):
282
"""
283
Shift hue channel of color by specified amount.
284
285
Parameters:
286
- color (color-spec): Input color specification
287
- shift (float): Hue shift amount in degrees
288
- space (str): Color space for hue shifting
289
290
Returns:
291
str: Color specification with shifted hue
292
"""
293
294
def scale_saturation(color, scale=1, space='hcl'):
295
"""
296
Scale saturation channel of color by specified factor.
297
298
Parameters:
299
- color (color-spec): Input color specification
300
- scale (float): Saturation scaling factor (1=no change)
301
- space (str): Color space for saturation scaling
302
303
Returns:
304
str: Color specification with scaled saturation
305
"""
306
307
def scale_luminance(color, scale=1, space='hcl'):
308
"""
309
Scale luminance channel of color by specified factor.
310
311
Parameters:
312
- color (color-spec): Input color specification
313
- scale (float): Luminance scaling factor (1=no change)
314
- space (str): Color space for luminance scaling
315
316
Returns:
317
str: Color specification with scaled luminance
318
"""
319
320
def to_hex(color, space='rgb', cycle=None, keep_alpha=True):
321
"""
322
Translate color specification to HEX string format.
323
324
Parameters:
325
- color (color-spec): Input color specification
326
- space (str): Source color space for conversion
327
- cycle (str/Cycle): Color cycle for named color resolution
328
- keep_alpha (bool): Preserve alpha channel in output
329
330
Returns:
331
str: Hexadecimal color string (#RRGGBB or #RRGGBBAA)
332
"""
333
334
def to_rgb(color, space='rgb', cycle=None):
335
"""
336
Translate color specification to RGB tuple.
337
338
Parameters:
339
- color (color-spec): Input color specification
340
- space (str): Source color space for conversion
341
- cycle (str/Cycle): Color cycle for named color resolution
342
343
Returns:
344
tuple: RGB color tuple (r, g, b) with values 0-1
345
"""
346
347
def to_rgba(color, space='rgb', cycle=None, clip=True):
348
"""
349
Translate color specification to RGBA tuple.
350
351
Parameters:
352
- color (color-spec): Input color specification
353
- space (str): Source color space for conversion
354
- cycle (str/Cycle): Color cycle for named color resolution
355
- clip (bool): Clip values to valid range
356
357
Returns:
358
tuple: RGBA color tuple (r, g, b, a) with values 0-1
359
"""
360
361
def to_xyz(color, space='hcl'):
362
"""
363
Translate color to channel values in specified colorspace.
364
365
Parameters:
366
- color (color-spec): Input color specification
367
- space (str): Target color space ('hcl', 'hsl', 'hsv', 'rgb')
368
369
Returns:
370
tuple: Color channel values in specified space
371
"""
372
373
def to_xyza(color, space='hcl'):
374
"""
375
Translate color to channel values with alpha in specified colorspace.
376
377
Parameters:
378
- color (color-spec): Input color specification
379
- space (str): Target color space ('hcl', 'hsl', 'hsv', 'rgb')
380
381
Returns:
382
tuple: Color channel values with alpha in specified space
383
"""
384
```
385
386
## Color Spaces
387
388
Proplot supports multiple color spaces for perceptually uniform color manipulation:
389
390
```python { .api }
391
COLOR_SPACES = {
392
'rgb': "Red-Green-Blue (standard display colors)",
393
'hcl': "Hue-Chroma-Luminance (perceptually uniform)",
394
'hsl': "Hue-Saturation-Lightness (intuitive adjustments)",
395
'hsv': "Hue-Saturation-Value (brightness-based)",
396
'lab': "CIE LAB (perceptually uniform)",
397
'luv': "CIE LUV (chromaticity-based)",
398
'xyz': "CIE XYZ (color matching functions)"
399
}
400
```
401
402
## Built-in Colormaps
403
404
Proplot includes extensive colormap collections organized by type:
405
406
```python { .api }
407
COLORMAP_CATEGORIES = {
408
'sequential': "Colormaps for ordered data (viridis, plasma, Blues, etc.)",
409
'diverging': "Colormaps for data with meaningful center (RdBu, BrBG, etc.)",
410
'cyclic': "Colormaps for circular data (twilight, hsv, etc.)",
411
'qualitative': "Colormaps for categorical data (tab10, Set1, etc.)",
412
'monochrome': "Single-hue colormaps (Greys, Blues, Reds, etc.)",
413
'geographic': "Colormaps for topographic data (terrain, ocean, etc.)"
414
}
415
```
416
417
## Usage Examples
418
419
### Basic Colormap Creation
420
421
```python
422
import proplot as pplt
423
import numpy as np
424
425
# Create custom colormap from colors
426
colors = ['red', 'white', 'blue']
427
cmap = pplt.Colormap(colors, name='rwb')
428
429
# Create from matplotlib colormap
430
cmap = pplt.Colormap('viridis', discrete=True, N=10)
431
432
# Perceptually uniform colormap
433
cmap = pplt.Colormap(['red', 'blue'], space='hcl')
434
```
435
436
### Color Manipulation
437
438
```python
439
# Adjust color properties
440
red = '#FF0000'
441
darker_red = pplt.scale_luminance(red, 0.7)
442
shifted_hue = pplt.shift_hue(red, 30) # Shift 30 degrees
443
less_saturated = pplt.scale_saturation(red, 0.5)
444
445
# Convert between formats
446
hex_color = pplt.to_hex((1, 0, 0)) # RGB to hex
447
rgba = pplt.to_rgba('red', space='rgb')
448
hcl = pplt.to_xyz('red', space='hcl')
449
```
450
451
### Color Cycles
452
453
```python
454
# Get colors from cycle
455
colors = pplt.get_colors('colorblind', 5)
456
457
# Create custom cycle
458
cycle = pplt.Cycle(['red', 'blue', 'green'], name='rgb')
459
460
# Sample from colormap
461
viridis_colors = pplt.get_colors('viridis', 8)
462
```
463
464
### Advanced Colormap Usage
465
466
```python
467
# Plotting with custom colormap
468
fig, axes = pplt.subplots(ncols=2)
469
470
# Continuous colormap
471
data = np.random.randn(20, 20)
472
cmap = pplt.Colormap(['navy', 'white', 'red'], space='hcl')
473
m = axes[0].contourf(data, cmap=cmap, levels=15)
474
axes[0].colorbar(m, loc='b')
475
476
# Discrete colormap with custom normalization
477
levels = [0, 2, 4, 8, 16, 32]
478
norm = pplt.Norm('segmented', levels=levels)
479
cmap_discrete = pplt.Colormap('plasma', discrete=True, N=len(levels)-1)
480
m2 = axes[1].contourf(data**2, cmap=cmap_discrete, norm=norm, levels=levels)
481
axes[1].colorbar(m2, loc='b')
482
```
483
484
### Colormap Registration and Management
485
486
```python
487
# Register custom colormap
488
colors = ['#440154', '#31688e', '#35b779', '#fde725']
489
pplt.register_cmaps(colors, name='custom_viridis')
490
491
# Use registered colormap
492
fig, ax = pplt.subplots()
493
ax.contourf(data, cmap='custom_viridis')
494
495
# Register from file
496
pplt.register_cmaps('scientific_colormap.json')
497
```
498
499
### Normalization Examples
500
501
```python
502
# Diverging normalization
503
data = np.random.randn(20, 20)
504
norm = pplt.Norm('diverging', vcenter=0)
505
ax.contourf(data, cmap='RdBu_r', norm=norm)
506
507
# Discrete levels
508
norm = pplt.Norm('discrete', levels=10)
509
ax.contourf(data, cmap='viridis', norm=norm)
510
511
# Segmented normalization
512
levels = [-2, -1, -0.5, 0, 0.5, 1, 2]
513
norm = pplt.Norm('segmented', levels=levels)
514
ax.contourf(data, cmap='RdBu_r', norm=norm, levels=levels)
515
```
516
517
### Color Space Exploration
518
519
```python
520
# Compare color adjustments in different spaces
521
base_color = 'red'
522
523
# HCL space (perceptually uniform)
524
hcl_lighter = pplt.set_luminance(base_color, 70, space='hcl')
525
hcl_desaturated = pplt.set_saturation(base_color, 30, space='hcl')
526
527
# HSL space (intuitive)
528
hsl_lighter = pplt.set_luminance(base_color, 70, space='hsl')
529
hsl_desaturated = pplt.set_saturation(base_color, 30, space='hsl')
530
531
# Plot comparison
532
colors_hcl = [base_color, hcl_lighter, hcl_desaturated]
533
colors_hsl = [base_color, hsl_lighter, hsl_desaturated]
534
535
fig, axes = pplt.subplots(ncols=2)
536
axes[0].bar(range(3), [1, 1, 1], color=colors_hcl)
537
axes[0].format(title='HCL Space Adjustments')
538
axes[1].bar(range(3), [1, 1, 1], color=colors_hsl)
539
axes[1].format(title='HSL Space Adjustments')
540
```
541
542
This comprehensive color system provides powerful tools for creating visually appealing and perceptually uniform visualizations while maintaining compatibility with matplotlib's existing color infrastructure.