'How to manually set a diverging color range

I am using Altair for Python and my current code uses a redyellowblue color scheme which uses the middle color (yellow) accordingly to my domainMid parameter.

color=alt.Color('Spline_WW_Diff_Trend:Q', scale=alt.Scale(scheme='redyellowblue',reverse=True, domain=[-3.57,2.270], domainMid=0, clamp=True), legend=alt.Legend(title="Trend"))

Which gives me: enter image description here

I need to replace the yellow color with the white color. I've switched scheme to range and tried different combinations of Scale parameters, but it doesn't respect my domainMid.

Example:

color=alt.Color('Spline_WW_Diff_Trend:Q', scale=alt.Scale(range=['#D4322C', 'white', '#4A74B4'],reverse=True, domain=[-3.57,2.270], domainMid=0, clamp=True), legend=alt.Legend(title="Trend"))

This gives me: enter image description here

You can notice that the first column (which is all value 0) is showing reddish and not white (as it was supposed to be).

How can I have the same result as in the color scheme (picture one), but, with white instead of yellow?

Edit:

The same goes for.

range=['blue', 'lightblue', 'white', 'pink', 'red']

The mid color is light-blue, not white.

enter image description here

Edit 05/12/2022:

Just to clarify, I would like to achieve this same color scheme: enter image description here enter image description here.

This heatmap was created in R, by using the RdYlBu color pallete (the one with 11 colors) and overwrite the middle (6th color) with white. Then, they increased the number of colors in the pallete to 99, to make the fade look more fluid. Does anyone has any idea on how to achieve that in Altair?



Solution 1:[1]

The easiest approach would be to set range='diverging', or to use one of the built-in diverging color schemes. For example:

import altair as alt
import pandas as pd
import numpy as np

df = pd.DataFrame({'x': np.arange(-10, 20)})

alt.Chart(df).mark_rect().encode(
    x='x:O',
    color=alt.Color('x:Q',
      scale=alt.Scale(domainMid=0, scheme='redblue'))
)

enter image description here

If it's important to you that the center value is exactly white, you could use a condition to override the colormap for this value. For example:

alt.Chart(df).mark_rect().encode(
    x='x:O',
    color=alt.condition(
      'datum.x == 0',
      alt.value('white'),
      alt.Color('x:Q', scale=alt.Scale(domainMid=0, scheme='redblue')))
)

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