如何保存自定义Matplotlib颜色条与色映射至.cpt文件跨程序复用?
Hey there! Let's break down your two Matplotlib colormap questions with practical, actionable solutions:
Question 1: Can I save a custom Matplotlib colormap for reuse elsewhere?
Absolutely! There are two straightforward ways to preserve your custom colormaps for later use:
Serialize with Pickle: Since
LinearSegmentedColormapobjects support pickling, you can save the entire colormap directly:import pickle # After creating your truncated cmap (from your example code) with open('truncated_cmap.pkl', 'wb') as f: pickle.dump(cmap, f) # To reload it later in another script with open('truncated_cmap.pkl', 'rb') as f: loaded_cmap = pickle.load(f)Save raw color values: Extract the gradient's color data as a numpy array, then rebuild the colormap when needed:
# Save 256 smooth color samples from your custom cmap color_values = cmap(np.linspace(0, 1, 256)) np.save('truncated_colors.npy', color_values) # Reload and reconstruct the colormap loaded_colors = np.load('truncated_colors.npy') loaded_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('truncated_cmap', loaded_colors)
Question 2: Can I save a custom Matplotlib colormap as a .cpt file for Panoply, MATLAB, etc.?
Yes! The .cpt format (used by GMT, Panoply, and MATLAB) defines color gradients using value ranges and corresponding RGB values. Here's how to convert your truncated colormap to this format, building on your existing code:
First, a quick primer on .cpt structure:
- Comment lines start with
#- A line declares the color model (e.g.,
# COLOR_MODEL = RGB)- Data lines follow the format:
z_start r0 g0 b0 z_end r1 g1 b1(RGB values are usually 0-255 integers)
Here's the full conversion code:
import matplotlib import matplotlib.pyplot as plt import numpy as np # Your existing code to create the truncated colormap cb = 'CMRmap' cmap = plt.get_cmap(cb) minval = 0.15 maxval = 0.95 npoints = 100 cmap = matplotlib.colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, npoints))) # Function to convert Matplotlib cmap to .cpt format def cmap_to_cpt(cmap, output_path, num_samples=256): # Generate smooth color samples from the colormap colors = cmap(np.linspace(0, 1, num_samples)) # Build the .cpt content line by line cpt_lines = [ "# Truncated CMRmap colormap (created from Matplotlib)", "# COLOR_MODEL = RGB" ] # Create gradient segments between adjacent color samples for i in range(num_samples - 1): z_start = i / (num_samples - 1) r0, g0, b0, _ = colors[i] z_end = (i + 1) / (num_samples - 1) r1, g1, b1, _ = colors[i + 1] # Convert RGB from 0-1 float to 0-255 integer line = f"{z_start:.6f} {int(r0*255)} {int(g0*255)} {int(b0*255)} {z_end:.6f} {int(r1*255)} {int(g1*255)} {int(b1*255)}" cpt_lines.append(line) # Write to the .cpt file with open(output_path, 'w') as f: f.write('\n'.join(cpt_lines)) # Run the conversion to create your .cpt file cmap_to_cpt(cmap, 'truncated_CMRmap.cpt')
Using the .cpt file in other tools:
- Panoply: Go to
Color Bar > Load Paletteand select your .cpt file directly. - MATLAB: Use the
cptreadfunction (or compatible third-party scripts) to load the palette, then apply it to your plots. - GMT: Reference the .cpt file in your plotting commands to apply the gradient.
This method creates a smooth, faithful copy of your custom Matplotlib colormap that works seamlessly across different programs.
内容的提问来源于stack exchange,提问作者tsherwen

