0
# Application Integration
1
2
Export colormaps to external applications and set up matplotlib integration features. These functions enable using CMasher colormaps across different visualization tools and environments.
3
4
## Capabilities
5
6
### Tableau Integration
7
8
Export CMasher colormaps to Tableau for use in business intelligence and data visualization workflows.
9
10
```python { .api }
11
def update_tableau_pref_file(dirname: str = ".") -> None:
12
"""
13
Update Tableau preferences file to include CMasher colormaps.
14
15
Parameters:
16
- dirname: Directory containing or where to create 'Preferences.tps' file
17
18
Returns:
19
None
20
21
Notes:
22
Creates or updates 'Preferences.tps' file with all CMasher colormaps.
23
Existing CMasher colormaps in the file are updated to current versions.
24
File is created if it doesn't exist.
25
"""
26
```
27
28
#### Usage Examples
29
30
```python
31
import cmasher as cmr
32
import os
33
34
# Update Tableau preferences in current directory
35
cmr.update_tableau_pref_file()
36
37
# Update preferences in specific directory
38
tableau_dir = os.path.expanduser('~/Documents/My Tableau Repository/Preferences')
39
os.makedirs(tableau_dir, exist_ok=True)
40
cmr.update_tableau_pref_file(tableau_dir)
41
42
# Update preferences in Tableau's default location (Windows example)
43
# tableau_default = r'C:\Users\{username}\Documents\My Tableau Repository\Preferences'
44
# cmr.update_tableau_pref_file(tableau_default)
45
```
46
47
#### Tableau Usage Workflow
48
49
```python
50
import cmasher as cmr
51
52
def setup_tableau_colormaps(tableau_preferences_path):
53
"""Complete setup workflow for Tableau integration."""
54
try:
55
# Update Tableau preferences
56
cmr.update_tableau_pref_file(tableau_preferences_path)
57
print("✓ Tableau preferences updated successfully")
58
59
# List available colormap types for Tableau
60
print("\nAvailable colormap types in Tableau:")
61
print("• Sequential (ordered-sequential): For ordered data")
62
print("• Diverging (ordered-diverging): For data with meaningful center")
63
print("• Cyclic (regular): For periodic/cyclical data")
64
65
# Show some example colormaps
66
sequential = cmr.get_cmap_list('sequential')[:5]
67
diverging = cmr.get_cmap_list('diverging')[:3]
68
cyclic = cmr.get_cmap_list('cyclic')
69
70
print(f"\nExample sequential: {sequential}")
71
print(f"Example diverging: {diverging}")
72
print(f"Example cyclic: {cyclic}")
73
74
print("\nAfter restarting Tableau, look for 'cmr.' prefixed colormaps")
75
76
except Exception as e:
77
print(f"✗ Setup failed: {e}")
78
79
# Example usage
80
# setup_tableau_colormaps('~/Documents/My Tableau Repository/Preferences')
81
```
82
83
### Matplotlib Legend Integration
84
85
Create colormap-based legend entries for matplotlib artists that use colormaps.
86
87
```python { .api }
88
def set_cmap_legend_entry(artist: Artist, label: str) -> None:
89
"""
90
Sets legend entry for matplotlib artist using colormap as icon.
91
92
Parameters:
93
- artist: Matplotlib artist object with 'cmap' attribute
94
- label: Label text for the legend entry
95
96
Returns:
97
None
98
99
Notes:
100
Creates miniature colormap representation as legend icon.
101
Overrides any existing legend entry for the artist.
102
103
Raises:
104
ValueError: If artist doesn't have 'cmap' attribute
105
"""
106
```
107
108
#### Usage Examples
109
110
```python
111
import cmasher as cmr
112
import matplotlib.pyplot as plt
113
import numpy as np
114
115
# Create scatter plot with colormap legend
116
data_x = np.random.rand(100)
117
data_y = np.random.rand(100)
118
colors = np.random.rand(100)
119
120
fig, ax = plt.subplots(figsize=(10, 6))
121
122
# Create scatter plot
123
scatter = ax.scatter(data_x, data_y, c=colors, cmap='cmr.rainforest', s=50)
124
125
# Set colormap legend entry
126
cmr.set_cmap_legend_entry(scatter, 'Data Points (Rainforest colormap)')
127
128
# Add legend
129
ax.legend()
130
ax.set_xlabel('X Values')
131
ax.set_ylabel('Y Values')
132
ax.set_title('Scatter Plot with Colormap Legend')
133
plt.show()
134
135
# Multiple colormapped artists
136
fig, ax = plt.subplots(figsize=(12, 8))
137
138
# Create multiple datasets with different colormaps
139
datasets = [
140
(np.random.rand(50), np.random.rand(50), 'cmr.ocean', 'Ocean Data'),
141
(np.random.rand(50), np.random.rand(50), 'cmr.ember', 'Fire Data'),
142
(np.random.rand(50), np.random.rand(50), 'cmr.jungle', 'Forest Data')
143
]
144
145
for x, y, cmap, label in datasets:
146
colors = np.random.rand(len(x))
147
scatter = ax.scatter(x, y, c=colors, cmap=cmap, s=60, alpha=0.7)
148
cmr.set_cmap_legend_entry(scatter, label)
149
150
ax.legend()
151
ax.set_title('Multiple Colormapped Datasets')
152
plt.show()
153
```
154
155
### Citation and Documentation
156
157
Get properly formatted citation information for scientific publications.
158
159
```python { .api }
160
def get_bibtex() -> None:
161
"""
162
Prints BibTeX entry for citing CMasher in publications.
163
164
Returns:
165
None
166
167
Notes:
168
Prints formatted BibTeX entry for the CMasher paper
169
(Van der Velden 2020, JOSS, 5, 2004).
170
"""
171
```
172
173
#### Usage Examples
174
175
```python
176
import cmasher as cmr
177
178
# Print citation information
179
cmr.get_bibtex()
180
181
# Output will be:
182
# @ARTICLE{2020JOSS....5.2004V,
183
# author = {{van der Velden}, Ellert},
184
# title = "{CMasher: Scientific colormaps for making accessible,
185
# informative and 'cmashing' plots}",
186
# journal = {The Journal of Open Source Software},
187
# keywords = {Python, science, colormaps, data visualization,
188
# plotting, Electrical Engineering and Systems Science - Image
189
# and Video Processing, Physics - Data Analysis, Statistics and
190
# Probability},
191
# year = 2020,
192
# month = feb,
193
# volume = {5},
194
# number = {46},
195
# eid = {2004},
196
# pages = {2004},
197
# doi = {10.21105/joss.02004},
198
# archivePrefix = {arXiv},
199
# eprint = {2003.01069},
200
# primaryClass = {eess.IV},
201
# adsurl = {https://ui.adsabs.harvard.edu/abs/2020JOSS....5.2004V},
202
# adsnote = {Provided by the SAO/NASA Astrophysics Data System}
203
# }
204
```
205
206
### Cross-Platform Integration Patterns
207
208
#### R Integration Guidance
209
210
```python
211
import cmasher as cmr
212
213
def show_r_integration_info():
214
"""Display information about using CMasher colormaps in R."""
215
print("CMasher colormaps can be used in R through several methods:")
216
print("\n1. Export colors as hex values:")
217
218
# Example of extracting colors for R
219
colors = cmr.take_cmap_colors('cmr.rainforest', 10, return_fmt='hex')
220
r_vector = "c('" + "', '".join(colors) + "')"
221
print(f" rainforest_colors <- {r_vector}")
222
223
print("\n2. Create R colormap function:")
224
print(" rainforest <- colorRampPalette(rainforest_colors)")
225
226
print("\n3. Use in ggplot2:")
227
print(" ggplot(data) + geom_point(aes(color=value)) +")
228
print(" scale_color_gradientn(colors=rainforest_colors)")
229
230
print(f"\nFor detailed instructions, see:")
231
print("https://cmasher.readthedocs.io/user/lang_usage/R.html")
232
233
show_r_integration_info()
234
```
235
236
#### Web Integration
237
238
```python
239
import cmasher as cmr
240
import json
241
242
def export_colormap_for_web(cmap_name, n_colors=256):
243
"""Export colormap data for web applications."""
244
245
# Extract colors in different formats
246
hex_colors = cmr.take_cmap_colors(f'cmr.{cmap_name}', n_colors, return_fmt='hex')
247
rgb_colors = cmr.take_cmap_colors(f'cmr.{cmap_name}', n_colors, return_fmt='int')
248
249
# Create web-friendly data structure
250
colormap_data = {
251
'name': cmap_name,
252
'type': cmr.get_cmap_type(f'cmr.{cmap_name}'),
253
'colors': {
254
'hex': hex_colors,
255
'rgb': rgb_colors,
256
'css': [f'rgb({r},{g},{b})' for r, g, b in rgb_colors]
257
},
258
'length': len(hex_colors)
259
}
260
261
# Save as JSON
262
with open(f'{cmap_name}_colormap.json', 'w') as f:
263
json.dump(colormap_data, f, indent=2)
264
265
print(f"Exported {cmap_name} colormap data for web use")
266
return colormap_data
267
268
# Export colormaps for web
269
web_data = export_colormap_for_web('rainforest', 64)
270
print(f"Exported {web_data['length']} colors")
271
```
272
273
#### Scientific Publication Workflow
274
275
```python
276
import cmasher as cmr
277
import matplotlib.pyplot as plt
278
import numpy as np
279
280
def create_publication_figure():
281
"""Create publication-ready figure with proper CMasher usage."""
282
283
# Set up publication-quality matplotlib settings
284
plt.rcParams.update({
285
'font.size': 12,
286
'font.family': 'sans-serif',
287
'axes.linewidth': 1.2,
288
'xtick.major.width': 1.2,
289
'ytick.major.width': 1.2,
290
'figure.dpi': 300
291
})
292
293
# Create example data
294
x = np.linspace(-3, 3, 100)
295
y = np.linspace(-3, 3, 100)
296
X, Y = np.meshgrid(x, y)
297
Z = np.sin(X) * np.cos(Y) * np.exp(-(X**2 + Y**2)/4)
298
299
# Create figure with CMasher colormap
300
fig, ax = plt.subplots(figsize=(8, 6))
301
302
# Use perceptually uniform colormap
303
im = ax.contourf(X, Y, Z, levels=20, cmap='cmr.iceburn')
304
305
# Add colorbar with proper labeling
306
cbar = plt.colorbar(im, ax=ax)
307
cbar.set_label('Amplitude', rotation=270, labelpad=20)
308
309
# Set labels and title
310
ax.set_xlabel('X coordinate')
311
ax.set_ylabel('Y coordinate')
312
ax.set_title('Scientific Data Visualization\nUsing CMasher Iceburn Colormap')
313
314
# Add citation note
315
fig.text(0.02, 0.02, 'Colormap: CMasher (van der Velden 2020)',
316
fontsize=8, style='italic')
317
318
plt.tight_layout()
319
plt.savefig('publication_figure.png', dpi=300, bbox_inches='tight')
320
plt.show()
321
322
# Print citation reminder
323
print("\nDon't forget to cite CMasher in your publication:")
324
cmr.get_bibtex()
325
326
# Create publication figure
327
create_publication_figure()
328
```
329
330
### Multi-Application Export
331
332
```python
333
import cmasher as cmr
334
import os
335
import json
336
import csv
337
338
def export_colormaps_multi_format(colormap_names, output_dir='colormap_exports'):
339
"""Export colormaps to multiple application formats."""
340
341
os.makedirs(output_dir, exist_ok=True)
342
343
for cmap_name in colormap_names:
344
print(f"Exporting {cmap_name}...")
345
346
# Create subdirectory for this colormap
347
cmap_dir = os.path.join(output_dir, cmap_name)
348
os.makedirs(cmap_dir, exist_ok=True)
349
350
# Extract colors in different formats
351
colors_float = cmr.take_cmap_colors(f'cmr.{cmap_name}', 256, return_fmt='float')
352
colors_hex = cmr.take_cmap_colors(f'cmr.{cmap_name}', 256, return_fmt='hex')
353
colors_int = cmr.take_cmap_colors(f'cmr.{cmap_name}', 256, return_fmt='int')
354
355
# Export for different applications
356
357
# 1. CSV for Excel/generic spreadsheet applications
358
with open(os.path.join(cmap_dir, f'{cmap_name}.csv'), 'w', newline='') as f:
359
writer = csv.writer(f)
360
writer.writerow(['Index', 'Red', 'Green', 'Blue', 'Hex'])
361
for i, (rgb, hex_color) in enumerate(zip(colors_float, colors_hex)):
362
writer.writerow([i, rgb[0], rgb[1], rgb[2], hex_color])
363
364
# 2. JSON for web applications
365
web_data = {
366
'name': cmap_name,
367
'type': cmr.get_cmap_type(f'cmr.{cmap_name}'),
368
'colors': {
369
'hex': colors_hex,
370
'rgb_normalized': colors_float,
371
'rgb_8bit': colors_int
372
}
373
}
374
with open(os.path.join(cmap_dir, f'{cmap_name}.json'), 'w') as f:
375
json.dump(web_data, f, indent=2)
376
377
# 3. Text files for various applications
378
with open(os.path.join(cmap_dir, f'{cmap_name}_hex.txt'), 'w') as f:
379
f.write('\n'.join(colors_hex))
380
381
# 4. Create standalone Python module
382
cmr.create_cmap_mod(cmap_name, save_dir=cmap_dir)
383
384
print(f"\nExported {len(colormap_names)} colormaps to {output_dir}/")
385
print("Formats: CSV, JSON, TXT, Python module")
386
387
# Export popular colormaps
388
popular_cmaps = ['rainforest', 'iceburn', 'ocean', 'wildfire', 'seasons']
389
export_colormaps_multi_format(popular_cmaps)
390
```