Skip to content

Instantly share code, notes, and snippets.

@akaanirban
Created March 13, 2021 21:14
Show Gist options
  • Save akaanirban/7deb55095f4d5bf72ec8d93feafe7599 to your computer and use it in GitHub Desktop.
Save akaanirban/7deb55095f4d5bf72ec8d93feafe7599 to your computer and use it in GitHub Desktop.
Get Color list from matplotlib Cmap

A small script to get the colors in a specific cmap as lists and then you can use them in your code. Main code was here: https://matplotlib.org/stable/gallery/color/colormap_reference.html Colormaps "Dark2" and "Set2" looks very good.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 16:08:06 2021

@author: Anirban Das
"""

import matplotlib.pyplot as plt
import numpy as np

cmaps = [('Qualitative', [
            'Pastel1', 'Pastel2', 'Paired', 'Accent',
            'Dark2', 'Set1', 'Set2', 'Set3',
            'tab10', 'tab20', 'tab20b', 'tab20c'])]


gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(cmap_category, cmap_list):
    # Create figure and adjust figure height to number of colormaps
    nrows = len(cmap_list)
    figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
    fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
    fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)

    axs[0].set_title(cmap_category + ' colormaps', fontsize=14)

    for ax, name in zip(axs, cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        print(f"Name {name}, {plt.get_cmap(name)}")
        # use plt.get_cmap(name).colors to get the color values
        ax.text(-.01, .5, name, va='center', ha='right', fontsize=10,
                transform=ax.transAxes)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axs:
        ax.set_axis_off()


for cmap_category, cmap_list in cmaps:
    plot_color_gradients(cmap_category, cmap_list)

plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment