0
# Colormap Manipulation
1
2
Combine and modify colormaps to create custom color schemes. These functions enable advanced colormap customization for specific visualization needs.
3
4
## Capabilities
5
6
### Colormap Combination
7
8
Blend multiple colormaps together at specified transition points to create composite color schemes.
9
10
```python { .api }
11
def combine_cmaps(
12
*cmaps: Colormap | str,
13
nodes: list[float] | None = None,
14
n_rgb_levels: int = 256,
15
combined_cmap_name: str = "combined_cmap"
16
) -> LinearSegmentedColormap:
17
"""
18
Create a composite colormap by combining multiple colormaps.
19
20
Parameters:
21
- *cmaps: Colormap objects or names to combine
22
- nodes: Transition points between colormaps in range [0, 1]
23
(None for equal divisions)
24
- n_rgb_levels: Number of RGB levels for each colormap segment
25
- combined_cmap_name: Name for the resulting colormap
26
27
Returns:
28
LinearSegmentedColormap: The composite colormap
29
30
Raises:
31
ValueError: If fewer than 2 colormaps provided, invalid nodes, etc.
32
TypeError: If invalid colormap types provided
33
"""
34
```
35
36
#### Usage Examples
37
38
```python
39
import cmasher as cmr
40
import matplotlib.pyplot as plt
41
import numpy as np
42
43
# Combine two colormaps with equal division
44
combined = cmr.combine_cmaps('cmr.ocean', 'cmr.ember')
45
46
# Combine three colormaps with custom transition points
47
custom_combined = cmr.combine_cmaps(
48
'cmr.arctic', 'cmr.neutral', 'cmr.ember',
49
nodes=[0.3, 0.7], # Transitions at 30% and 70%
50
combined_cmap_name='arctic_neutral_ember'
51
)
52
53
# Use combined colormap in plot
54
data = np.random.rand(20, 20)
55
plt.imshow(data, cmap=combined)
56
plt.colorbar()
57
plt.title('Combined Colormap Example')
58
plt.show()
59
60
# Combine with different proportions
61
fire_ice = cmr.combine_cmaps(
62
'cmr.freeze', 'cmr.ember',
63
nodes=[0.2], # 20% freeze, 80% ember
64
n_rgb_levels=512 # Higher resolution
65
)
66
```
67
68
### Colormap Subsetting
69
70
Extract portions of existing colormaps to create focused color ranges.
71
72
```python { .api }
73
def get_sub_cmap(
74
cmap: str | Colormap,
75
start: float,
76
stop: float,
77
*,
78
N: int | None = None
79
) -> ListedColormap:
80
"""
81
Creates a colormap using a subset of colors from an existing colormap.
82
83
Parameters:
84
- cmap: Source colormap name or object
85
- start: Start of range to extract (0.0 to 1.0)
86
- stop: End of range to extract (0.0 to 1.0)
87
- N: Number of discrete colors (None for continuous)
88
89
Returns:
90
ListedColormap: Subset colormap with '_sub' or '_qual' suffix
91
92
Notes:
93
Use at least 128 colors for smooth gradients. Setting N creates
94
a qualitative colormap with discrete colors.
95
"""
96
```
97
98
#### Usage Examples
99
100
```python
101
import cmasher as cmr
102
import matplotlib.pyplot as plt
103
import numpy as np
104
105
# Extract first 80% of rainforest colormap
106
partial_cmap = cmr.get_sub_cmap('cmr.rainforest', 0, 0.8)
107
108
# Extract middle portion of a diverging colormap
109
center_cmap = cmr.get_sub_cmap('cmr.iceburn', 0.2, 0.8)
110
111
# Create qualitative colormap from sequential colormap
112
qual_colors = cmr.get_sub_cmap('cmr.tropical', 0.1, 0.9, N=8)
113
114
# Use in visualization
115
data = np.random.rand(15, 15)
116
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
117
118
axes[0].imshow(data, cmap='cmr.rainforest')
119
axes[0].set_title('Original Rainforest')
120
121
axes[1].imshow(data, cmap=partial_cmap)
122
axes[1].set_title('Partial Rainforest (0-80%)')
123
124
axes[2].imshow(data, cmap=qual_colors)
125
axes[2].set_title('Qualitative Subset')
126
127
plt.tight_layout()
128
plt.show()
129
```
130
131
### Advanced Combination Patterns
132
133
#### Sequential to Diverging Conversion
134
135
```python
136
import cmasher as cmr
137
138
# Create diverging colormap from two sequential colormaps
139
def create_diverging_from_sequential(cmap1, cmap2, center_point=0.5):
140
"""Create diverging colormap from two sequential colormaps."""
141
# Reverse first colormap and combine
142
reversed_cmap1 = f"{cmap1}_r" if not cmap1.endswith('_r') else cmap1[:-2]
143
144
return cmr.combine_cmaps(
145
reversed_cmap1, cmap2,
146
nodes=[center_point],
147
combined_cmap_name=f"div_{cmap1}_{cmap2}"
148
)
149
150
# Create custom diverging colormap
151
custom_div = create_diverging_from_sequential('cmr.arctic', 'cmr.ember')
152
```
153
154
#### Multi-Segment Colormaps
155
156
```python
157
import cmasher as cmr
158
159
# Create complex multi-segment colormap
160
spectrum = cmr.combine_cmaps(
161
'cmr.arctic', # Blue range
162
'cmr.emerald', # Green range
163
'cmr.amber', # Yellow range
164
'cmr.ember', # Red range
165
nodes=[0.25, 0.5, 0.75],
166
combined_cmap_name='custom_spectrum',
167
n_rgb_levels=1024
168
)
169
```
170
171
#### Proportional Combinations
172
173
```python
174
import cmasher as cmr
175
176
def proportional_combine(cmaps_and_weights):
177
"""Combine colormaps with specific proportions."""
178
total_weight = sum(cmaps_and_weights.values())
179
180
# Calculate cumulative nodes
181
nodes = []
182
cumulative = 0
183
cmap_list = list(cmaps_and_weights.keys())
184
185
for i, (cmap, weight) in enumerate(cmaps_and_weights.items()):
186
if i < len(cmap_list) - 1: # Don't add node for last colormap
187
cumulative += weight / total_weight
188
nodes.append(cumulative)
189
190
return cmr.combine_cmaps(*cmap_list, nodes=nodes)
191
192
# Example: 40% ocean, 30% neutral, 30% ember
193
weighted_cmap = proportional_combine({
194
'cmr.ocean': 0.4,
195
'cmr.neutral': 0.3,
196
'cmr.ember': 0.3
197
})
198
```
199
200
### Colormap Modification Workflows
201
202
#### Creating Themed Collections
203
204
```python
205
import cmasher as cmr
206
207
def create_themed_variants(base_cmap, theme_cmaps, theme_name):
208
"""Create multiple variants of a base colormap with different themes."""
209
variants = {}
210
211
for i, theme_cmap in enumerate(theme_cmaps):
212
# Create combination with different proportions
213
variant = cmr.combine_cmaps(
214
base_cmap, theme_cmap,
215
nodes=[0.7], # 70% base, 30% theme
216
combined_cmap_name=f"{theme_name}_variant_{i}"
217
)
218
variants[f"{theme_name}_{i}"] = variant
219
220
return variants
221
222
# Create ocean-themed variants
223
ocean_variants = create_themed_variants(
224
'cmr.neutral',
225
['cmr.ocean', 'cmr.tropical', 'cmr.arctic'],
226
'ocean_theme'
227
)
228
```
229
230
#### Dynamic Range Adjustment
231
232
```python
233
import cmasher as cmr
234
235
def adjust_colormap_range(cmap_name, data_range=(0.1, 0.9)):
236
"""Adjust colormap to focus on specific data range."""
237
return cmr.get_sub_cmap(
238
cmap_name,
239
data_range[0],
240
data_range[1]
241
)
242
243
# Focus on middle range for low-contrast data
244
focused_cmap = adjust_colormap_range('cmr.rainforest', (0.3, 0.7))
245
```
246
247
#### Colormap Harmonization
248
249
```python
250
import cmasher as cmr
251
import matplotlib.pyplot as plt
252
import numpy as np
253
254
def harmonize_colormaps(*cmap_names, n_colors=256):
255
"""Create harmonized versions of multiple colormaps."""
256
harmonized = {}
257
258
for cmap_name in cmap_names:
259
# Extract subset that harmonizes well
260
base_cmap = cmr.get_sub_cmap(cmap_name, 0.1, 0.9)
261
harmonized[cmap_name.replace('cmr.', '')] = base_cmap
262
263
return harmonized
264
265
# Create harmonized set for multi-panel plots
266
harmonized_set = harmonize_colormaps(
267
'cmr.rainforest', 'cmr.ocean', 'cmr.ember'
268
)
269
270
# Use in multi-panel visualization
271
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
272
data_sets = [np.random.rand(10, 10) for _ in range(3)]
273
274
for ax, (name, cmap), data in zip(axes, harmonized_set.items(), data_sets):
275
im = ax.imshow(data, cmap=cmap)
276
ax.set_title(f'Harmonized {name.title()}')
277
plt.colorbar(im, ax=ax)
278
279
plt.tight_layout()
280
plt.show()
281
```
282
283
### Error Handling and Validation
284
285
```python
286
import cmasher as cmr
287
288
def safe_combine_cmaps(*cmaps, **kwargs):
289
"""Safely combine colormaps with error handling."""
290
try:
291
return cmr.combine_cmaps(*cmaps, **kwargs)
292
except ValueError as e:
293
print(f"Combination error: {e}")
294
return None
295
except TypeError as e:
296
print(f"Type error: {e}")
297
return None
298
299
# Example usage with error handling
300
result = safe_combine_cmaps('cmr.ocean') # Will fail - need 2+ colormaps
301
if result is None:
302
print("Using default colormap instead")
303
result = 'cmr.ocean'
304
```