'How to create a custom diverging colormap in matplotlib?

I want to create a colormap similar to "RdBu" in matplotlib. traditional "RdBu"

I want to make the colormap in this sequence light blue->dark blue-> black(center)->dark red->light red. Something like this. Required colormap

So it is similar to "RdBu" but white changes to black & dark colors interchanged with light colors. So it is just inverting the "RdBu" colors. I don't know how to do it.



Solution 1:[1]

I made a simple tool that helps to create colormaps and generates the required code:

https://eltos.github.io/gradient/#4C71FF-0025B3-000000-C7030D-FC4A53

Screenshot

-->

And the code you get from the download button:

#!/usr/bin/env python

from matplotlib.colors import LinearSegmentedColormap

my_gradient = LinearSegmentedColormap.from_list('my_gradient', (
                 # Edit this gradient at https://eltos.github.io/gradient/#4C71FF-0025B3-000000-C7030D-FC4A53
                 (0.000, (0.298, 0.443, 1.000)),
                 (0.250, (0.000, 0.145, 0.702)),
                 (0.500, (0.000, 0.000, 0.000)),
                 (0.750, (0.780, 0.012, 0.051)),
                 (1.000, (0.988, 0.290, 0.325))))


if __name__ == '__main__':
    import numpy as np
    from matplotlib import pyplot as plt
    
    plt.imshow([np.arange(1000)], aspect="auto", cmap=my_gradient)
    plt.show()

Solution 2:[2]

I wanted to create diverging colormaps by simply combining existing ones.

Here's the code:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors
from typing import List, Tuple

def get_hex_col(cmap) -> List[str]:
    """Return list of hex colors for cmap"""
    return [colors.rgb2hex(cmap(i)) for i in range(cmap.N)]

def get_cmap_list(
        cmap_name: str, length_n: int) -> [str]:
    """Create a classified colormap of length N
    """
    cmap = plt.cm.get_cmap(cmap_name, length_n)
    cmap_list = get_hex_col(cmap)
    return cmap_list

def get_diverging_colormap(
        cmap_diverging:Tuple[str,str], color_count: int = k_classes):
    """Create a diverging colormap from two existing with k classes"""
    div_cmaps: List[List[str]] = []
    for cmap_name in cmap_diverging:
        cmap_list = get_cmap_list(
            cmap_name, length_n=color_count)
        div_cmaps.append(cmap_list)
    div_cmaps[1] = list(reversed(div_cmaps[1]))
    cmap_nodata_list = div_cmaps[1] + div_cmaps[0]
    return colors.ListedColormap(cmap_nodata_list)

# apply
cmaps_diverging: Tuple[str] = ("OrRd", "Purples")
cmap = get_diverging_colormap(cmaps_diverging)

# visualize
def display_hex_colors(hex_colors: List[str]):
    """Visualize a list of hex colors using pandas"""
    df = pd.DataFrame(hex_colors).T
    df.columns = hex_colors
    df.iloc[0,0:len(hex_colors)] = ""
    display(df.style.apply(lambda x: apply_formatting(x, hex_colors)))

display_hex_colors(cmap.colors)

Output for example "OrRd" and "Purples": enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eltos
Solution 2 Alex