Skip to content Skip to sidebar Skip to footer

Creating A Diverging Color Palette With A "midrange" Instead Of A "midpoint"

I am using python seaborn package to generate a diverging color palette (seaborn.diverging_palette). I can choose my two extremity colors, and define if the center is light-> wh

Solution 1:

It seems the sep parameter can take any integer between 1 and 254. The fraction of the colourmap that will be covered by the midpoint colour will be equal to sep/256.

Perhaps an easy way to visualise this is to use the seaborn.palplot, with n=256 to split the palette up into 256 colours.

Here is a palette with sep = 1:

sns.palplot(sns.diverging_palette(0, 255, sep=1, n=256))

enter image description here

And here is a palette with sep = 8

sns.palplot(sns.diverging_palette(0, 255, sep=8, n=256))

enter image description here

Here is sep = 64 (i.e. one quarter of the palette is the midpoint colour)

sns.palplot(sns.diverging_palette(0, 255, sep=64, n=256))

enter image description here

Here is sep = 128 (i.e. one half is the midpoint colour)

sns.palplot(sns.diverging_palette(0, 255, sep=128, n=256))

enter image description here

And here is sep = 254 (i.e. all but the colours on the very edge of the palette are the midpoint colour)

sns.palplot(sns.diverging_palette(0, 255, sep=254, n=256))

enter image description here

Your specific palette

So, for your case where you have a range of 0 - 20, but a midpoint range of 7 - 13, you would want the fraction of the palette to be the midpoint to be 6/20. To convert that to sep, we need to multiply by 256, so we get sep = 256 * 6 / 20 = 76.8. However, sep must be an integer, so lets use 77.

Here is a script to make a diverging palette, and plot a colorbar to show that using sep = 77 leaves the correct midpoint colour between 7 and 13:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

# Create your palette
cmap = sns.diverging_palette(0,255,sep=77, as_cmap=True)

# Some data with a range of 0 to 20
x = np.linspace(0,20,20).reshape(4,5)

# Plot a heatmap (I turned off the cbar here, so I can create it later with ticks spaced every integer)
ax = sns.heatmap(x, cmap=cmap, vmin=0, vmax=20, cbar = False)

# Grab the heatmap from the axes
hmap = ax.collections[0]

# make a colorbar with ticks spaced every integer
cmap = plt.gcf().colorbar(hmap)
cmap.set_ticks(range(21))

plt.show()

enter image description here

Post a Comment for "Creating A Diverging Color Palette With A "midrange" Instead Of A "midpoint""