1

I am struggling to create the color bar that I want in matplotlib. Ideally it would look like more like this (lows are greys, highs are bright red:

enter image description here

However I am getting the following:

enter image description here
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

colors_top = cm.get_cmap('Greys_r', 128)
colors_bot = cm.get_cmap('Reds', 128)
cmap_grey_red = ListedColormap(
    np.vstack((
        colors_top(np.linspace(0, 1, 128)),
        colors_bot(np.linspace(0, 1, 128))
    )), name='GreyRed'
)

How can I correct this color bar?

SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • 1
    This appears related: https://stackoverflow.com/a/25996834/2864250 – dubbbdan Jul 21 '22 at 17:39
  • @dubbbdan yes somewhat related. `LinearSegmentedColormap.from_list("GreyRed",['grey', "r"])` is closer, still not as nice as I would like it though... thanks for the pointer! – SumNeuron Jul 21 '22 at 18:29

1 Answers1

2

Whatever approach you choose, you will still have to map the colors to whatever scale the color bar is displaying using the norm argument. Here is what I could quickly come up with:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

x,y,c = zip(*np.random.rand(30,3)*4-2)

cvals  = [-2., 0,  2]
colors = ["dimgray","salmon","red"]

norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)

plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()

enter image description here

The color ramp you provided is diverging (e.g., white in the middle), If you want a smoother transition, you could just develop a color map with three colors.

dubbbdan
  • 2,650
  • 1
  • 25
  • 43