Scientific colormaps for making accessible, informative and 'cmashing' plots
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Export colormaps to external applications and set up matplotlib integration features. These functions enable using CMasher colormaps across different visualization tools and environments.
Export CMasher colormaps to Tableau for use in business intelligence and data visualization workflows.
def update_tableau_pref_file(dirname: str = ".") -> None:
"""
Update Tableau preferences file to include CMasher colormaps.
Parameters:
- dirname: Directory containing or where to create 'Preferences.tps' file
Returns:
None
Notes:
Creates or updates 'Preferences.tps' file with all CMasher colormaps.
Existing CMasher colormaps in the file are updated to current versions.
File is created if it doesn't exist.
"""import cmasher as cmr
import os
# Update Tableau preferences in current directory
cmr.update_tableau_pref_file()
# Update preferences in specific directory
tableau_dir = os.path.expanduser('~/Documents/My Tableau Repository/Preferences')
os.makedirs(tableau_dir, exist_ok=True)
cmr.update_tableau_pref_file(tableau_dir)
# Update preferences in Tableau's default location (Windows example)
# tableau_default = r'C:\Users\{username}\Documents\My Tableau Repository\Preferences'
# cmr.update_tableau_pref_file(tableau_default)import cmasher as cmr
def setup_tableau_colormaps(tableau_preferences_path):
"""Complete setup workflow for Tableau integration."""
try:
# Update Tableau preferences
cmr.update_tableau_pref_file(tableau_preferences_path)
print("✓ Tableau preferences updated successfully")
# List available colormap types for Tableau
print("\nAvailable colormap types in Tableau:")
print("• Sequential (ordered-sequential): For ordered data")
print("• Diverging (ordered-diverging): For data with meaningful center")
print("• Cyclic (regular): For periodic/cyclical data")
# Show some example colormaps
sequential = cmr.get_cmap_list('sequential')[:5]
diverging = cmr.get_cmap_list('diverging')[:3]
cyclic = cmr.get_cmap_list('cyclic')
print(f"\nExample sequential: {sequential}")
print(f"Example diverging: {diverging}")
print(f"Example cyclic: {cyclic}")
print("\nAfter restarting Tableau, look for 'cmr.' prefixed colormaps")
except Exception as e:
print(f"✗ Setup failed: {e}")
# Example usage
# setup_tableau_colormaps('~/Documents/My Tableau Repository/Preferences')Create colormap-based legend entries for matplotlib artists that use colormaps.
def set_cmap_legend_entry(artist: Artist, label: str) -> None:
"""
Sets legend entry for matplotlib artist using colormap as icon.
Parameters:
- artist: Matplotlib artist object with 'cmap' attribute
- label: Label text for the legend entry
Returns:
None
Notes:
Creates miniature colormap representation as legend icon.
Overrides any existing legend entry for the artist.
Raises:
ValueError: If artist doesn't have 'cmap' attribute
"""import cmasher as cmr
import matplotlib.pyplot as plt
import numpy as np
# Create scatter plot with colormap legend
data_x = np.random.rand(100)
data_y = np.random.rand(100)
colors = np.random.rand(100)
fig, ax = plt.subplots(figsize=(10, 6))
# Create scatter plot
scatter = ax.scatter(data_x, data_y, c=colors, cmap='cmr.rainforest', s=50)
# Set colormap legend entry
cmr.set_cmap_legend_entry(scatter, 'Data Points (Rainforest colormap)')
# Add legend
ax.legend()
ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')
ax.set_title('Scatter Plot with Colormap Legend')
plt.show()
# Multiple colormapped artists
fig, ax = plt.subplots(figsize=(12, 8))
# Create multiple datasets with different colormaps
datasets = [
(np.random.rand(50), np.random.rand(50), 'cmr.ocean', 'Ocean Data'),
(np.random.rand(50), np.random.rand(50), 'cmr.ember', 'Fire Data'),
(np.random.rand(50), np.random.rand(50), 'cmr.jungle', 'Forest Data')
]
for x, y, cmap, label in datasets:
colors = np.random.rand(len(x))
scatter = ax.scatter(x, y, c=colors, cmap=cmap, s=60, alpha=0.7)
cmr.set_cmap_legend_entry(scatter, label)
ax.legend()
ax.set_title('Multiple Colormapped Datasets')
plt.show()Get properly formatted citation information for scientific publications.
def get_bibtex() -> None:
"""
Prints BibTeX entry for citing CMasher in publications.
Returns:
None
Notes:
Prints formatted BibTeX entry for the CMasher paper
(Van der Velden 2020, JOSS, 5, 2004).
"""import cmasher as cmr
# Print citation information
cmr.get_bibtex()
# Output will be:
# @ARTICLE{2020JOSS....5.2004V,
# author = {{van der Velden}, Ellert},
# title = "{CMasher: Scientific colormaps for making accessible,
# informative and 'cmashing' plots}",
# journal = {The Journal of Open Source Software},
# keywords = {Python, science, colormaps, data visualization,
# plotting, Electrical Engineering and Systems Science - Image
# and Video Processing, Physics - Data Analysis, Statistics and
# Probability},
# year = 2020,
# month = feb,
# volume = {5},
# number = {46},
# eid = {2004},
# pages = {2004},
# doi = {10.21105/joss.02004},
# archivePrefix = {arXiv},
# eprint = {2003.01069},
# primaryClass = {eess.IV},
# adsurl = {https://ui.adsabs.harvard.edu/abs/2020JOSS....5.2004V},
# adsnote = {Provided by the SAO/NASA Astrophysics Data System}
# }import cmasher as cmr
def show_r_integration_info():
"""Display information about using CMasher colormaps in R."""
print("CMasher colormaps can be used in R through several methods:")
print("\n1. Export colors as hex values:")
# Example of extracting colors for R
colors = cmr.take_cmap_colors('cmr.rainforest', 10, return_fmt='hex')
r_vector = "c('" + "', '".join(colors) + "')"
print(f" rainforest_colors <- {r_vector}")
print("\n2. Create R colormap function:")
print(" rainforest <- colorRampPalette(rainforest_colors)")
print("\n3. Use in ggplot2:")
print(" ggplot(data) + geom_point(aes(color=value)) +")
print(" scale_color_gradientn(colors=rainforest_colors)")
print(f"\nFor detailed instructions, see:")
print("https://cmasher.readthedocs.io/user/lang_usage/R.html")
show_r_integration_info()import cmasher as cmr
import json
def export_colormap_for_web(cmap_name, n_colors=256):
"""Export colormap data for web applications."""
# Extract colors in different formats
hex_colors = cmr.take_cmap_colors(f'cmr.{cmap_name}', n_colors, return_fmt='hex')
rgb_colors = cmr.take_cmap_colors(f'cmr.{cmap_name}', n_colors, return_fmt='int')
# Create web-friendly data structure
colormap_data = {
'name': cmap_name,
'type': cmr.get_cmap_type(f'cmr.{cmap_name}'),
'colors': {
'hex': hex_colors,
'rgb': rgb_colors,
'css': [f'rgb({r},{g},{b})' for r, g, b in rgb_colors]
},
'length': len(hex_colors)
}
# Save as JSON
with open(f'{cmap_name}_colormap.json', 'w') as f:
json.dump(colormap_data, f, indent=2)
print(f"Exported {cmap_name} colormap data for web use")
return colormap_data
# Export colormaps for web
web_data = export_colormap_for_web('rainforest', 64)
print(f"Exported {web_data['length']} colors")import cmasher as cmr
import matplotlib.pyplot as plt
import numpy as np
def create_publication_figure():
"""Create publication-ready figure with proper CMasher usage."""
# Set up publication-quality matplotlib settings
plt.rcParams.update({
'font.size': 12,
'font.family': 'sans-serif',
'axes.linewidth': 1.2,
'xtick.major.width': 1.2,
'ytick.major.width': 1.2,
'figure.dpi': 300
})
# Create example data
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y) * np.exp(-(X**2 + Y**2)/4)
# Create figure with CMasher colormap
fig, ax = plt.subplots(figsize=(8, 6))
# Use perceptually uniform colormap
im = ax.contourf(X, Y, Z, levels=20, cmap='cmr.iceburn')
# Add colorbar with proper labeling
cbar = plt.colorbar(im, ax=ax)
cbar.set_label('Amplitude', rotation=270, labelpad=20)
# Set labels and title
ax.set_xlabel('X coordinate')
ax.set_ylabel('Y coordinate')
ax.set_title('Scientific Data Visualization\nUsing CMasher Iceburn Colormap')
# Add citation note
fig.text(0.02, 0.02, 'Colormap: CMasher (van der Velden 2020)',
fontsize=8, style='italic')
plt.tight_layout()
plt.savefig('publication_figure.png', dpi=300, bbox_inches='tight')
plt.show()
# Print citation reminder
print("\nDon't forget to cite CMasher in your publication:")
cmr.get_bibtex()
# Create publication figure
create_publication_figure()import cmasher as cmr
import os
import json
import csv
def export_colormaps_multi_format(colormap_names, output_dir='colormap_exports'):
"""Export colormaps to multiple application formats."""
os.makedirs(output_dir, exist_ok=True)
for cmap_name in colormap_names:
print(f"Exporting {cmap_name}...")
# Create subdirectory for this colormap
cmap_dir = os.path.join(output_dir, cmap_name)
os.makedirs(cmap_dir, exist_ok=True)
# Extract colors in different formats
colors_float = cmr.take_cmap_colors(f'cmr.{cmap_name}', 256, return_fmt='float')
colors_hex = cmr.take_cmap_colors(f'cmr.{cmap_name}', 256, return_fmt='hex')
colors_int = cmr.take_cmap_colors(f'cmr.{cmap_name}', 256, return_fmt='int')
# Export for different applications
# 1. CSV for Excel/generic spreadsheet applications
with open(os.path.join(cmap_dir, f'{cmap_name}.csv'), 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Index', 'Red', 'Green', 'Blue', 'Hex'])
for i, (rgb, hex_color) in enumerate(zip(colors_float, colors_hex)):
writer.writerow([i, rgb[0], rgb[1], rgb[2], hex_color])
# 2. JSON for web applications
web_data = {
'name': cmap_name,
'type': cmr.get_cmap_type(f'cmr.{cmap_name}'),
'colors': {
'hex': colors_hex,
'rgb_normalized': colors_float,
'rgb_8bit': colors_int
}
}
with open(os.path.join(cmap_dir, f'{cmap_name}.json'), 'w') as f:
json.dump(web_data, f, indent=2)
# 3. Text files for various applications
with open(os.path.join(cmap_dir, f'{cmap_name}_hex.txt'), 'w') as f:
f.write('\n'.join(colors_hex))
# 4. Create standalone Python module
cmr.create_cmap_mod(cmap_name, save_dir=cmap_dir)
print(f"\nExported {len(colormap_names)} colormaps to {output_dir}/")
print("Formats: CSV, JSON, TXT, Python module")
# Export popular colormaps
popular_cmaps = ['rainforest', 'iceburn', 'ocean', 'wildfire', 'seasons']
export_colormaps_multi_format(popular_cmaps)Install with Tessl CLI
npx tessl i tessl/pypi-cmasher