### Install cmocean with pip Source: https://github.com/matplotlib/cmocean/blob/main/README.md Use this command to install the cmocean package using pip. ```bash pip install cmocean ``` -------------------------------- ### Install cmocean Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Use pip to install the cmocean package. For enhanced functionality including plotting tools, install with the 'plots' extra. ```bash pip install cmocean ``` ```bash conda install -c conda-forge cmocean ``` ```bash pip install "cmocean[plots]" ``` -------------------------------- ### Install cmocean with plots submodule Source: https://github.com/matplotlib/cmocean/blob/main/README.md Install cmocean with the 'plots' submodule to include viscm and colorspacious dependencies. This is useful for advanced plotting functionalities. ```bash pip install "cmocean[plots]" ``` -------------------------------- ### Install cmocean with Anaconda Source: https://github.com/matplotlib/cmocean/blob/main/README.md Use this command to install the cmocean package from the conda-forge channel. ```bash conda install -c conda-forge cmocean ``` -------------------------------- ### Evaluate Colormap Quality with viscm using cmocean.plots.wrap_viscm Source: https://context7.com/matplotlib/cmocean/llms.txt Wraps the `viscm` tool to generate a comprehensive perceptual quality analysis panel for a single colormap. This includes perceptual deltas, colorblind simulations, and lightness profiles. Requires `cmocean[plots]` which installs `viscm`. ```python import cmocean # Analyse the 'delta' colormap (diverging: river discharge / sea floor topography) cmocean.plots.wrap_viscm(cmocean.cm.delta, dpi=150, saveplot=True) # Output: viscm analysis panel displayed and saved as # 'cmocean_eval_delta.png' and 'cmocean_eval_delta.pdf' ``` -------------------------------- ### Clip Top Part of a Colormap by Percent Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Shows how to clip the top percentage of a colormap, for example, removing the top 20% of the 'oxy' colormap. ```python cmocean.tools.clip_colors(cm.oxy, 0.0, 0.8) ``` -------------------------------- ### Get All Available Colormap Names Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Retrieves a list of all available colormap names within the cmocean package. ```python cmocean.cm.cmapnames ``` -------------------------------- ### `cmocean.plots.test` Source: https://context7.com/matplotlib/cmocean/llms.txt Visualizes a colormap's perceptual lightness (CAM02-UCS J channel) as a scatter plot. This helps in assessing if the colormap is perceptually uniform and monotonic. Requires the `cmocean[plots]` installation. ```APIDOC ## `cmocean.plots.test` — Visualize a Colormap's Perceptual Lightness Plots a colormap's perceptual lightness (CAM02-UCS J channel) as a scatter plot, allowing quick visual inspection of whether the colormap is perceptually uniform and monotonic. Requires the `cmocean[plots]` installation. ### Parameters - `cmap` (matplotlib.colors.Colormap): The colormap to test. - `fig` (matplotlib.figure.Figure, optional): The figure to plot on. If None, a new figure is created. - `ax` (matplotlib.axes.Axes, optional): The axes to plot on. If None, new axes are created. ### Request Example ```python import cmocean import matplotlib.pyplot as plt # Test a single colormap fig, axes = plt.subplots(1, 3, figsize=(15, 4)) for ax, cmap in zip(axes, [cmocean.cm.thermal, cmocean.cm.haline, cmocean.cm.balance]): cmocean.plots.test(cmap, fig=fig, ax=ax) plt.tight_layout() plt.savefig('lightness_test.png', dpi=150) plt.close() ``` ### Response - Displays a scatter plot of the colormap's perceptual lightness. ``` -------------------------------- ### Visualize Colormap Perceptual Lightness with cmocean.plots.test Source: https://context7.com/matplotlib/cmocean/llms.txt Use this function to plot a colormap's perceptual lightness (CAM02-UCS J channel) as a scatter plot. This helps in visually assessing if the colormap is perceptually uniform and monotonic. Requires `cmocean[plots]` installation. ```python import cmocean import matplotlib.pyplot as plt # Test a single colormap fig, axes = plt.subplots(1, 3, figsize=(15, 4)) for ax, cmap in zip(axes, [cmocean.cm.thermal, cmocean.cm.haline, cmocean.cm.balance]): cmocean.plots.test(cmap, fig=fig, ax=ax) plt.tight_layout() plt.savefig('lightness_test.png', dpi=150) plt.close() # Output: three lightness scatter plots — uniform ramps indicate perceptual uniformity ``` -------------------------------- ### Quick Pcolor Preview of a Colormap with cmocean.plots.quick_plot Source: https://context7.com/matplotlib/cmocean/llms.txt Generates a simple pcolor grid to preview a colormap. Optionally saves the figure to a file. Use `fname` to specify the output filename. The `N` parameter controls the number of grid cells. ```python import cmocean import matplotlib.pyplot as plt # Quick preview of the 'topo' colormap (land + ocean combined) cmocean.plots.quick_plot(cmocean.cm.topo, fname='topo_preview', N=20) # Output: displays pcolor grid and saves 'topo_preview.png' ``` ```python # Embed in an existing figure fig, ax = plt.subplots() cmocean.plots.quick_plot(cmocean.cm.rain, fig=fig, ax=ax, N=15) plt.savefig('rain_preview.png', dpi=150) plt.close() # Output: pcolor grid with colorbar showing the rain colormap ``` -------------------------------- ### `cmocean.plots.quick_plot` Source: https://context7.com/matplotlib/cmocean/llms.txt Renders a simple gradient pcolor grid for a fast visual preview of any colormap. The figure can optionally be saved to a file. ```APIDOC ## `cmocean.plots.quick_plot` — Quick Pcolor Preview of a Colormap Renders a simple gradient pcolor grid to give a fast visual preview of any colormap. Optionally saves the figure to a file. ### Parameters - `cmap` (matplotlib.colors.Colormap): The colormap to preview. - `fname` (str, optional): If provided, the figure will be saved to this filename (e.g., 'my_colormap_preview.png'). - `N` (int, optional): The number of color steps to use in the pcolor grid. Defaults to 20. - `fig` (matplotlib.figure.Figure, optional): The figure to plot on. If None, a new figure is created. - `ax` (matplotlib.axes.Axes, optional): The axes to plot on. If None, new axes are created. ### Request Example ```python import cmocean import matplotlib.pyplot as plt # Quick preview of the 'topo' colormap (land + ocean combined) cmocean.plots.quick_plot(cmocean.cm.topo, fname='topo_preview', N=20) # Embed in an existing figure fig, ax = plt.subplots() cmocean.plots.quick_plot(cmocean.cm.rain, fig=fig, ax=ax, N=15) plt.savefig('rain_preview.png', dpi=150) plt.close() ``` ### Response - Displays a pcolor grid preview of the colormap. If `fname` is provided, the figure is saved to that file. ``` -------------------------------- ### Access Colormap Instances Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Shows how to access specific colormap instances from the cmocean.cm module. ```python cmocean.cm.haline ``` -------------------------------- ### Render Full Gallery of All Colormaps with cmocean.plots.plot_gallery Source: https://context7.com/matplotlib/cmocean/llms.txt Creates a publication-ready gallery image displaying all cmocean colormaps as color strips alongside their grayscale equivalents. Set `saveplot=True` to save the gallery to PNG and PDF files. Requires `cmocean[plots]`. ```python import cmocean # Display gallery on screen cmocean.plots.plot_gallery(saveplot=False) # Save gallery to PNG and PDF cmocean.plots.plot_gallery(saveplot=True) # Output: 'cmocean_gallery.png' and 'cmocean_gallery.pdf' saved to current directory ``` -------------------------------- ### Clip Colormap by Percent Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Demonstrates clipping both ends of a colormap by a specified percentage to reduce the lightness range. ```python cmocean.tools.clip_colors(cm.thermal, 0.1, 0.9) ``` -------------------------------- ### Access and Plot cmocean Colormaps Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Demonstrates how to access colormap instances from cmocean.cm and plot them using matplotlib. All available colormap names can be found in cmocean.cm.cmapnames. ```python import cmocean.cm as cm import matplotlib.pyplot as plt plt.plot(*cm.cmap_examples.values()) ``` -------------------------------- ### Access Reversed and Inverted Lightness Colormaps Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Illustrates accessing colormaps that are both reversed and have inverted lightness by appending '_r_i' or '_i_r'. ```python cmocean.cm.balance_i_r ``` -------------------------------- ### Access Inverted Lightness Colormaps Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Shows how to access colormaps with inverted lightness by appending '_i' to the colormap name, useful for light backgrounds. ```python cmocean.cm.balance_i ``` -------------------------------- ### `cmocean.tools.print_colormaps` Source: https://context7.com/matplotlib/cmocean/llms.txt Samples colormaps at specified levels and returns or saves the RGB arrays. ```APIDOC ## `cmocean.tools.print_colormaps` — Export Colormaps to RGB Text Files Samples one or more colormaps at `N` evenly spaced positions and returns (and optionally saves) the resulting RGB arrays. This is the mechanism cmocean itself uses to generate its bundled `*-rgb.txt` data files. ### Parameters - **cmaps**: A list of colormap objects to sample. - **N**: The number of evenly spaced positions to sample the colormaps (default is 256). - **returnrgb**: If True, returns the RGB arrays. If False, only saves to files if `savefiles` is True. - **savefiles**: If True, saves the RGB values to text files named after the colormaps (e.g., 'topo-rgb.txt'). ### Request Example ```python import cmocean # Return RGB arrays for thermal and haline at 256 levels (no file save) rgb_list = cmocean.tools.print_colormaps( [cmocean.cm.thermal, cmocean.cm.haline], N=256, returnrgb=True, savefiles=False ) thermal_rgb = rgb_list[0] # shape: (256, 3), values in [0, 1] haline_rgb = rgb_list[1] print(thermal_rgb.shape) # (256, 3) print(thermal_rgb[0]) # first color (darkest end): [r, g, b] print(thermal_rgb[-1]) # last color (lightest end): [r, g, b] # Save the RGB values for 'topo' to a text file 'topo-rgb.txt' cmocean.tools.print_colormaps( [cmocean.cm.topo], N=256, returnrgb=False, savefiles=True ) ``` ### Response If `returnrgb` is True, returns a list of NumPy arrays, where each array contains the RGB values for a colormap. If `savefiles` is True, creates text files containing the RGB data. ``` -------------------------------- ### Create Colormap from RGB Input Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Generates a colormap instance using the cmocean.tools.cmap function, given an RGB input array and the desired number of colors (N). ```python rgbin = ((0,1,0), (0,0,1), (1,0,0)) cmap = cmocean.tools.cmap(rgbin, N=10) ``` -------------------------------- ### Access Reversed Colormaps Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Demonstrates how to access reversed versions of colormaps by appending '_r' to the colormap name, similar to matplotlib. ```python cmocean.cm.balance_r ``` -------------------------------- ### `cmocean.plots.wrap_viscm` Source: https://context7.com/matplotlib/cmocean/llms.txt Wraps the `viscm` tool to produce a comprehensive perceptual quality analysis panel for a single colormap. This includes perceptual deltas and colorblind simulations. ```APIDOC ## `cmocean.plots.wrap_viscm` — Evaluate Colormap Quality with viscm Wraps the `viscm` tool to produce a comprehensive perceptual quality analysis panel for a single colormap, including perceptual deltas, colourblind simulations, and lightness profile. Requires `cmocean[plots]` (installs `viscm`). ### Parameters - `cmap` (matplotlib.colors.Colormap): The colormap to analyze. - `dpi` (int, optional): The resolution for saved plots. Defaults to 150. - `saveplot` (bool, optional): If True, saves the analysis panel to PNG and PDF files. Defaults to True. ### Request Example ```python import cmocean # Analyse the 'delta' colormap (diverging: river discharge / sea floor topography) cmocean.plots.wrap_viscm(cmocean.cm.delta, dpi=150, saveplot=True) ``` ### Response - Displays a viscm analysis panel and optionally saves it to 'cmocean_eval_.png' and 'cmocean_eval_.pdf'. ``` -------------------------------- ### Crop Colormap by Percentage with cmocean.tools.crop_by_percent Source: https://context7.com/matplotlib/cmocean/llms.txt Trims a specified percentage from one or both ends of a colormap. Useful for removing extreme colors from sequential or diverging maps. ```python import cmocean import numpy as np import matplotlib.pyplot as plt data = np.random.rand(20, 20) * 10 # values 0–10 # Remove top 20% of oxy colormap (cuts off the yellow extreme) oxy_trimmed_max = cmocean.tools.crop_by_percent(cmocean.cm.oxy, 20, which='max') # Remove bottom 20% (cuts off the deep red end) oxy_trimmed_min = cmocean.tools.crop_by_percent(cmocean.cm.oxy, 20, which='min') # Remove 10% from both ends of balance balance_trimmed = cmocean.tools.crop_by_percent(cmocean.cm.balance, 10, which='both') fig, axes = plt.subplots(1, 3, figsize=(15, 4)) for ax, cmap, title in zip(axes, [oxy_trimmed_max, oxy_trimmed_min, balance_trimmed], ['oxy -20% max', 'oxy -20% min', 'balance -10% both']): pcm = ax.pcolormesh(data, cmap=cmap) fig.colorbar(pcm, ax=ax) ax.set_title(title) plt.tight_layout() plt.savefig('crop_by_percent_example.png', dpi=150) plt.close() # Output: three plots showing differently trimmed colormaps ``` -------------------------------- ### `cmocean.plots.plot_gallery` Source: https://context7.com/matplotlib/cmocean/llms.txt Generates a publication-ready gallery image showing every cmocean colormap as a color strip alongside its grayscale equivalent. This facilitates easy evaluation of all available colormaps. ```APIDOC ## `cmocean.plots.plot_gallery` — Render a Full Gallery of All Colormaps Generates a publication-ready gallery image showing every cmocean colormap as a color strip alongside its grayscale equivalent, making it easy to evaluate all available options at once. Requires `cmocean[plots]`. ### Parameters - `saveplot` (bool, optional): If True, saves the gallery to 'cmocean_gallery.png' and 'cmocean_gallery.pdf'. Defaults to False. ### Request Example ```python import cmocean # Display gallery on screen cmocean.plots.plot_gallery(saveplot=False) # Save gallery to PNG and PDF cmocean.plots.plot_gallery(saveplot=True) ``` ### Response - Displays the colormap gallery on screen or saves it to 'cmocean_gallery.png' and 'cmocean_gallery.pdf' if `saveplot` is True. ``` -------------------------------- ### Clip Colormap by Data Values Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Illustrates clipping a colormap based on the intended data values, allowing the function to determine the cropping amount. This is useful for mapping specific data ranges to colormap segments. ```python cmocean.tools.clip_colors(cm.topo, 0, 100) ``` -------------------------------- ### Plot Lightness Profiles for All Colormaps with cmocean.plots.plot_lightness Source: https://context7.com/matplotlib/cmocean/llms.txt Plots the perceptual lightness (J) values for all cmocean colormaps on a single axes, colored by the colormap itself. This allows for comparison of uniformity and contrast across the entire collection. Requires `cmocean[plots]`. ```python import cmocean # Display lightness comparison on screen cmocean.plots.plot_lightness(saveplot=False) # Save to file cmocean.plots.plot_lightness(saveplot=True) # Output: 'cmocean_lightness.png' and 'cmocean_lightness.pdf' saved to current directory ``` -------------------------------- ### Accessing and Using Cmocean Colormaps Source: https://context7.com/matplotlib/cmocean/llms.txt Demonstrates how to access the 22 available cmocean colormaps, including their reversed and inverted variants, and how to use them directly in matplotlib plots. ```APIDOC ## Accessing and Using Cmocean Colormaps ### Description All 22 cmocean colormaps are accessible as attributes of `cmocean.cm`. Each colormap also has a reversed variant (suffix `_r`), an inverted-lightness variant (suffix `_i`), and a combined reversed-inverted variant (suffix `_r_i` or `_i_r`). All colormaps are also registered in matplotlib under the `cmo.` namespace. ### Usage ```python import cmocean import matplotlib.pyplot as plt import numpy as np # List all available colormap names print(cmocean.cm.cmapnames) # Access colormaps directly as attributes cmap_thermal = cmocean.cm.thermal # sequential: temperature cmap_haline = cmocean.cm.haline # sequential: salinity cmap_oxy = cmocean.cm.oxy # sequential: dissolved oxygen cmap_balance = cmocean.cm.balance # diverging: balance cmap_phase = cmocean.cm.phase # circular: phase # Reversed variant cmap_thermal_r = cmocean.cm.thermal_r # Inverted-lightness variant (dark <-> light flipped) cmap_thermal_i = cmocean.cm.thermal_i # Use by matplotlib string name via 'cmo.' prefix lon = np.linspace(-100, -80, 50) lat = np.linspace(25, 35, 50) LON, LAT = np.meshgrid(lon, lat) SST = 20 + 10 * np.random.rand(50, 50) # synthetic sea surface temperature fig, ax = plt.subplots() pcm = ax.pcolormesh(LON, LAT, SST, cmap='cmo.thermal', vmin=20, vmax=30) fig.colorbar(pcm, ax=ax, label='Temperature (°C)') ax.set_title('Sea Surface Temperature') plt.tight_layout() plt.savefig('sst_plot.png', dpi=150) plt.close() ``` ### Output `pcolormesh` plot saved to `sst_plot.png` using the thermal colormap. ``` -------------------------------- ### Print Colormaps to Text Files Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Saves all colormaps with 256 RGB entries to text files using the cmocean.tools.print_colormaps function. ```python cmaps = cmocean.cm.cmap_d cmocean.tools.print_colormaps(cmaps) ``` -------------------------------- ### Lighten Colormap with Alpha Transparency Source: https://context7.com/matplotlib/cmocean/llms.txt Creates a lighter version of an existing colormap by applying a uniform alpha transparency value. This is useful for rendering colormaps over white backgrounds. ```python import cmocean import numpy as np import matplotlib.pyplot as plt # Lighten the 'matter' colormap to 60% opacity light_matter = cmocean.tools.lighten(cmocean.cm.matter, alpha=0.6) data = np.random.rand(30, 30) fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # Original colormap axes[0].pcolormesh(data, cmap=cmocean.cm.matter) axes[0].set_title('Original matter') # Lightened colormap axes[1].pcolormesh(data, cmap=light_matter) axes[1].set_title('Lightened matter (alpha=0.6)') plt.tight_layout() plt.savefig('lighten_example.png', dpi=150) plt.close() # Output: side-by-side comparison of full vs. alpha-lightened colormap ``` -------------------------------- ### `cmocean.tools.crop_by_percent` Source: https://context7.com/matplotlib/cmocean/llms.txt A convenience function to crop a colormap by a specified percentage from one or both ends, useful for trimming extreme colors. ```APIDOC ## `cmocean.tools.crop_by_percent` — Crop a Colormap by Percentage A convenience wrapper around `crop()` that removes a specified percentage from one or both ends of any colormap, useful for trimming extreme colors from sequential or diverging maps. ### Parameters - **cmap**: Colormap object - **percent**: The percentage of the colormap to remove from the ends. - **which**: Specifies which end(s) to crop. Can be 'min', 'max', or 'both'. ### Request Example ```python import cmocean import numpy as np import matplotlib.pyplot as plt data = np.random.rand(20, 20) * 10 # values 0–10 # Remove top 20% of oxy colormap (cuts off the yellow extreme) oxy_trimmed_max = cmocean.tools.crop_by_percent(cmocean.cm.oxy, 20, which='max') # Remove bottom 20% (cuts off the deep red end) oxy_trimmed_min = cmocean.tools.crop_by_percent(cmocean.cm.oxy, 20, which='min') # Remove 10% from both ends of balance balance_trimmed = cmocean.tools.crop_by_percent(cmocean.cm.balance, 10, which='both') fig, axes = plt.subplots(1, 3, figsize=(15, 4)) for ax, cmap, title in zip(axes, [oxy_trimmed_max, oxy_trimmed_min, balance_trimmed], ['oxy -20% max', 'oxy -20% min', 'balance -10% both']): pcm = ax.pcolormesh(data, cmap=cmap) fig.colorbar(pcm, ax=ax) ax.set_title(title) plt.tight_layout() plt.savefig('crop_by_percent_example.png', dpi=150) plt.close() ``` ### Response Returns a new colormap object that has been cropped by the specified percentage. ``` -------------------------------- ### Scatter Plot with cmocean Colormap Source: https://context7.com/matplotlib/cmocean/llms.txt Demonstrates using a cmocean colormap ('thermal') with a matplotlib scatter plot. Ensure matplotlib and numpy are imported. ```python import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() sc = ax.scatter(np.random.rand(200), np.random.rand(200), c=np.random.rand(200), cmap='cmo.thermal', s=40) fig.colorbar(sc, ax=ax, label='Temperature proxy') plt.savefig('scatter_thermal.png', dpi=150) plt.close() ``` -------------------------------- ### Export Colormap as Dictionary with cmocean.tools.get_dict Source: https://context7.com/matplotlib/cmocean/llms.txt Converts a colormap object into a dictionary format compatible with matplotlib.colors.LinearSegmentedColormap.from_dict. Useful for programmatic colormap construction or export. ```python import cmocean import matplotlib.colors as mcolors # Get the dictionary representation of the haline colormap haline_dict = cmocean.tools.get_dict(cmocean.cm.haline, N=256) # haline_dict keys: 'red', 'green', 'blue' # Each value is a list of (position, color_left, color_right) tuples print(list(haline_dict.keys())) # ['red', 'green', 'blue'] print(haline_dict['red'][:3]) # first three red channel entries # Reconstruct a LinearSegmentedColormap from the dictionary reconstructed = mcolors.LinearSegmentedColormap('haline_reconstructed', haline_dict, N=256) import matplotlib.pyplot as plt import numpy as np data = np.linspace(0, 40, 400).reshape(20, 20) # salinity range 0–40 PSU fig, ax = plt.subplots() pcm = ax.pcolormesh(data, cmap=reconstructed, vmin=0, vmax=40) fig.colorbar(pcm, ax=ax, label='Salinity (PSU)') plt.savefig('haline_reconstructed.png', dpi=150) plt.close() # Output: pcolormesh using reconstructed haline colormap ``` -------------------------------- ### cmocean.tools.lighten — Lighten a Colormap with Alpha Transparency Source: https://context7.com/matplotlib/cmocean/llms.txt Returns a new colormap derived from an existing one by applying a uniform alpha (transparency) value less than 1, making the colormap appear lighter when rendered over a white background. ```APIDOC ## cmocean.tools.lighten — Lighten a Colormap with Alpha Transparency ### Description Returns a new colormap derived from an existing one with all colors assigned a uniform alpha (transparency) value less than 1, making the colormap appear lighter when rendered over a white background. ### Usage ```python import cmocean import numpy as np import matplotlib.pyplot as plt # Lighten the 'matter' colormap to 60% opacity light_matter = cmocean.tools.lighten(cmocean.cm.matter, alpha=0.6) data = np.random.rand(30, 30) fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # Original colormap axes[0].pcolormesh(data, cmap=cmocean.cm.matter) axes[0].set_title('Original matter') # Lightened colormap axes[1].pcolormesh(data, cmap=light_matter) axes[1].set_title('Lightened matter (alpha=0.6)') plt.tight_layout() plt.savefig('lighten_example.png', dpi=150) plt.close() ``` ### Output Side-by-side comparison of full vs. alpha-lightened colormap. ``` -------------------------------- ### Lighten a Colormap for Overlay Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Uses cmocean.tools.lighten() to adjust the alpha value of a colormap, making it suitable for overlaying contours or lines. ```python cmocean.tools.lighten(cm.amp, alpha=0.5) ``` -------------------------------- ### `cmocean.plots.plot_lightness` Source: https://context7.com/matplotlib/cmocean/llms.txt Plots the perceptual lightness (J) values of all cmocean colormaps on a single axes, colored by the colormap itself. This allows for comparison of uniformity and contrast across the entire collection. ```APIDOC ## `cmocean.plots.plot_lightness` — Plot Lightness Profiles for All Colormaps Plots the perceptual lightness (J) values of all cmocean colormaps on a single axes, coloured by the colormap itself, to compare uniformity and contrast across the whole collection. Requires `cmocean[plots]`. ### Parameters - `saveplot` (bool, optional): If True, saves the plot to 'cmocean_lightness.png' and 'cmocean_lightness.pdf'. Defaults to False. ### Request Example ```python import cmocean # Display lightness comparison on screen cmocean.plots.plot_lightness(saveplot=False) # Save to file cmocean.plots.plot_lightness(saveplot=True) ``` ### Response - Displays a plot comparing the lightness profiles of all cmocean colormaps on screen or saves it to 'cmocean_lightness.png' and 'cmocean_lightness.pdf' if `saveplot` is True. ``` -------------------------------- ### Crop a Diverging Colormap with cmocean.tools.crop Source: https://context7.com/matplotlib/cmocean/llms.txt Crops a diverging colormap to align its pivot with asymmetric data ranges. Use when your data's vmin/vmax are not equidistant from the pivot, ensuring correct colorbar alignment. ```python import cmocean import numpy as np import matplotlib.pyplot as plt # Data has asymmetric range: vmin=-2, vmax=5, pivot=0 vmin, vmax, pivot = -2, 5, 0 cropped_curl = cmocean.tools.crop(cmocean.cm.curl, vmin, vmax, pivot) A = np.random.uniform(vmin, vmax, (10, 10)) fig, axes = plt.subplots(1, 2, figsize=(12, 4)) # Uncropped: white (pivot) is not centred in range pcm0 = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.curl) fig.colorbar(pcm0, ax=axes[0]) axes[0].set_title('Uncropped curl') # Cropped: pivot is correctly balanced pcm1 = axes[1].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cropped_curl) fig.colorbar(pcm1, ax=axes[1]) axes[1].set_title('Cropped curl (vmin=-2, vmax=5, pivot=0)') plt.tight_layout() plt.savefig('crop_example.png', dpi=150) plt.close() # Output: correct diverging colormap with pivot aligned to zero # Example with dmax — crop equal ends symmetrically vmin, vmax, pivot, dmax = -10, 10, 0, 7 cropped_delta = cmocean.tools.crop(cmocean.cm.delta, vmin, vmax, pivot, dmax=dmax) # Only the inner ±7 range of the colormap is kept ``` -------------------------------- ### Access and Use Cmocean Colormaps Source: https://context7.com/matplotlib/cmocean/llms.txt Demonstrates how to access, list, and use cmocean colormaps, including sequential, diverging, and circular types, as well as their reversed and inverted variants. Colormaps can be used directly by name in matplotlib plotting functions. ```python import cmocean import matplotlib.pyplot as plt import numpy as np # List all available colormap names print(cmocean.cm.cmapnames) # ['thermal', 'haline', 'solar', 'ice', 'gray', 'oxy', 'deep', # 'dense', 'algae', 'matter', 'turbid', 'speed', 'amp', 'tempo', # 'rain', 'phase', 'topo', 'balance', 'delta', 'curl', 'diff', 'tarn'] # Access colormaps directly as attributes cmap_thermal = cmocean.cm.thermal # sequential: temperature cmap_haline = cmocean.cm.haline # sequential: salinity cmap_oxy = cmocean.cm.oxy # sequential: dissolved oxygen cmap_balance = cmocean.cm.balance # diverging: balance cmap_phase = cmocean.cm.phase # circular: phase # Reversed variant cmap_thermal_r = cmocean.cm.thermal_r # Inverted-lightness variant (dark <-> light flipped) cmap_thermal_i = cmocean.cm.thermal_i # Use by matplotlib string name via 'cmo.' prefix lon = np.linspace(-100, -80, 50) lat = np.linspace(25, 35, 50) LON, LAT = np.meshgrid(lon, lat) SST = 20 + 10 * np.random.rand(50, 50) # synthetic sea surface temperature fig, ax = plt.subplots() pcm = ax.pcolormesh(LON, LAT, SST, cmap='cmo.thermal', vmin=20, vmax=30) fig.colorbar(pcm, ax=ax, label='Temperature (°C)') ax.set_title('Sea Surface Temperature') plt.tight_layout() plt.savefig('sst_plot.png', dpi=150) plt.close() # Output: pcolormesh plot saved to sst_plot.png using the thermal colormap ``` -------------------------------- ### Export Colormaps to RGB Text Files with cmocean.tools.print_colormaps Source: https://context7.com/matplotlib/cmocean/llms.txt Samples colormaps at specified levels and returns or saves the RGB arrays. This function is used internally by cmocean to generate RGB data files. ```python import cmocean # Return RGB arrays for thermal and haline at 256 levels (no file save) rgb_list = cmocean.tools.print_colormaps( [cmocean.cm.thermal, cmocean.cm.haline], N=256, returnrgb=True, savefiles=False ) thermal_rgb = rgb_list[0] # shape: (256, 3), values in [0, 1] haline_rgb = rgb_list[1] print(thermal_rgb.shape) # (256, 3) print(thermal_rgb[0]) # first color (darkest end): [r, g, b] print(thermal_rgb[-1]) # last color (lightest end): [r, g, b] # Save the RGB values for 'topo' to a text file 'topo-rgb.txt' cmocean.tools.print_colormaps( [cmocean.cm.topo], N=256, returnrgb=False, savefiles=True ) # Output: file 'topo-rgb.txt' written with 256 rows of R G B values ``` -------------------------------- ### `cmocean.tools.crop` Source: https://context7.com/matplotlib/cmocean/llms.txt Crops one or both ends of a diverging colormap to align its pivot with asymmetric data ranges, ensuring correct colorbar alignment. ```APIDOC ## `cmocean.tools.crop` — Crop a Diverging Colormap to Match Asymmetric Data Ranges Crops one or both ends of a diverging colormap so that the colormap pivot (e.g., zero) aligns correctly with asymmetric `vmin`/`vmax` values, preventing the colorbar from being misaligned with the data range. ### Parameters - **cmap**: Colormap object - **vmin**: Minimum data value - **vmax**: Maximum data value - **pivot**: The data value that should be centered in the colormap - **dmax**: Optional. If provided, crops symmetrically from both ends up to this value. ### Request Example ```python import cmocean import numpy as np import matplotlib.pyplot as plt # Data has asymmetric range: vmin=-2, vmax=5, pivot=0 vmin, vmax, pivot = -2, 5, 0 cropped_curl = cmocean.tools.crop(cmocean.cm.curl, vmin, vmax, pivot) A = np.random.uniform(vmin, vmax, (10, 10)) fig, axes = plt.subplots(1, 2, figsize=(12, 4)) # Uncropped: white (pivot) is not centred in range pcm0 = axes[0].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cmocean.cm.curl) fig.colorbar(pcm0, ax=axes[0]) axes[0].set_title('Uncropped curl') # Cropped: pivot is correctly balanced pcm1 = axes[1].pcolormesh(A, vmin=vmin, vmax=vmax, cmap=cropped_curl) fig.colorbar(pcm1, ax=axes[1]) axes[1].set_title('Cropped curl (vmin=-2, vmax=5, pivot=0)') plt.tight_layout() plt.savefig('crop_example.png', dpi=150) plt.close() ``` ### Response Returns a new colormap object that has been cropped. ``` -------------------------------- ### cmocean.tools.cmap — Create a Colormap from RGB Values Source: https://context7.com/matplotlib/cmocean/llms.txt Generates a `matplotlib.colors.LinearSegmentedColormap` by interpolating between provided RGB triplets or hex color strings, allowing for custom colormap creation. ```APIDOC ## cmocean.tools.cmap — Create a Colormap from RGB Values ### Description Generates a `matplotlib.colors.LinearSegmentedColormap` from an array of RGB triplets or hex color strings, interpolating between provided colors to produce a smooth colormap with `N` levels. ### Usage ```python import cmocean import numpy as np import matplotlib.pyplot as plt # Create a custom colormap from RGB triplets (values 0–1 or 0–255) custom_rgb = np.array([ [0.10, 0.20, 0.50], [0.30, 0.60, 0.80], [0.90, 0.95, 1.00], ]) custom_cmap = cmocean.tools.cmap(custom_rgb, N=256) print(custom_cmap.name) # mycmap # Create from hex strings hex_colors = ['#1a3350', '#4a90d9', '#e8f4fc'] hex_cmap = cmocean.tools.cmap(np.array(hex_colors), N=128) # Use the custom colormap in a plot data = np.random.rand(20, 20) fig, ax = plt.subplots() im = ax.imshow(data, cmap=custom_cmap) plt.colorbar(im, ax=ax, label='Custom scale') plt.savefig('custom_cmap_plot.png', dpi=150) plt.close() ``` ### Output `imshow` plot using the custom interpolated colormap. ``` -------------------------------- ### Create Custom Colormap from RGB or Hex Source: https://context7.com/matplotlib/cmocean/llms.txt Generates a matplotlib colormap by interpolating between specified RGB triplets or hex color strings. The `N` parameter controls the number of color levels in the resulting colormap. ```python import cmocean import numpy as np import matplotlib.pyplot as plt # Create a custom colormap from RGB triplets (values 0–1 or 0–255) custom_rgb = np.array([ [0.10, 0.20, 0.50], [0.30, 0.60, 0.80], [0.90, 0.95, 1.00], ]) custom_cmap = cmocean.tools.cmap(custom_rgb, N=256) print(custom_cmap.name) # mycmap # Create from hex strings hex_colors = ['#1a3350', '#4a90d9', '#e8f4fc'] hex_cmap = cmocean.tools.cmap(np.array(hex_colors), N=128) # Use the custom colormap in a plot data = np.random.rand(20, 20) fig, ax = plt.subplots() im = ax.imshow(data, cmap=custom_cmap) plt.colorbar(im, ax=ax, label='Custom scale') plt.savefig('custom_cmap_plot.png', dpi=150) plt.close() # Output: imshow plot using the custom interpolated colormap ``` -------------------------------- ### `cmocean.tools.get_dict` Source: https://context7.com/matplotlib/cmocean/llms.txt Converts a colormap object into a dictionary format compatible with `matplotlib.colors.LinearSegmentedColormap.from_dict`. ```APIDOC ## `cmocean.tools.get_dict` — Export a Colormap as a LinearSegmentedColormap Dictionary Converts a colormap object into the dictionary format expected by `matplotlib.colors.LinearSegmentedColormap.from_dict`, useful for programmatic colormap construction or export. ### Parameters - **cmap**: Colormap object - **N**: The number of discrete levels in the colormap (default is 256). ### Request Example ```python import cmocean import matplotlib.colors as mcolors # Get the dictionary representation of the haline colormap haline_dict = cmocean.tools.get_dict(cmocean.cm.haline, N=256) # haline_dict keys: 'red', 'green', 'blue' # Each value is a list of (position, color_left, color_right) tuples print(list(haline_dict.keys())) # ['red', 'green', 'blue'] print(haline_dict['red'][:3]) # first three red channel entries # Reconstruct a LinearSegmentedColormap from the dictionary reconstructed = mcolors.LinearSegmentedColormap('haline_reconstructed', haline_dict, N=256) import matplotlib.pyplot as plt import numpy as np data = np.linspace(0, 40, 400).reshape(20, 20) # salinity range 0–40 PSU fig, ax = plt.subplots() pcm = ax.pcolormesh(data, cmap=reconstructed, vmin=0, vmax=40) fig.colorbar(pcm, ax=ax, label='Salinity (PSU)') plt.savefig('haline_reconstructed.png', dpi=150) plt.close() ``` ### Response Returns a dictionary representing the colormap, suitable for `matplotlib.colors.LinearSegmentedColormap.from_dict`. ``` -------------------------------- ### Register cmocean Colormaps with Matplotlib Source: https://github.com/matplotlib/cmocean/blob/main/docs/source/index.md Explains that cmocean colormaps are registered with matplotlib, allowing them to be called directly by their name, e.g., 'cmo.amp'. ```python import cmocean.cm as cmo import matplotlib.pyplot as plt plt.register_cmap(name='amp', cmap=cmo.amp) plt.pcolormesh(range(10), range(10), range(100).reshape(10,10), cmap='amp') ``` -------------------------------- ### Use cmocean Colormaps with Matplotlib by String Name Source: https://context7.com/matplotlib/cmocean/llms.txt All cmocean colormaps are registered with matplotlib under the `cmo.` namespace upon import. This allows them to be used directly as strings in matplotlib functions, eliminating the need for explicit `cmocean.cm` references. ```python import cmocean # triggers registration import matplotlib.pyplot as plt import numpy as np depth = np.random.uniform(0, 5000, (40, 40)) # ocean depth in metres salinity = np.random.uniform(30, 40, (40, 40)) # salinity in PSU vorticity = np.random.uniform(-1, 1, (40, 40)) # relative vorticity fig, axes = plt.subplots(1, 3, figsize=(18, 5)) pcm0 = axes[0].pcolormesh(depth, cmap='cmo.deep', vmin=0, vmax=5000) pcm1 = axes[1].pcolormesh(salinity, cmap='cmo.haline', vmin=30, vmax=40) pcm2 = axes[2].pcolormesh(vorticity,cmap='cmo.curl', vmin=-1, vmax=1) for ax, pcm, label in zip(axes, [pcm0, pcm1, pcm2], ['Depth (m)', 'Salinity (PSU)', 'Vorticity (s⁻¹)']): fig.colorbar(pcm, ax=ax, label=label) plt.tight_layout() plt.savefig('ocean_properties.png', dpi=150) plt.close() # Output: three-panel figure using deep, haline, and curl colormaps by string name ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.