Heatmap Color Scale

I need all data above 2 on the heatmap to be red, but the range for the data changes for different data sets. For example, in the first plot, the data ranges from 0 to 3, but in the second plot, it ranges from 0 to 6.
Is there a way to make all values above 2 red no matter how large the range is?

To define such a colorscale you need a custom function. I write it down in Python and you can translate it to plotly.js.

``````import plotly.graph_objects as go
import numpy as np

def custom_colorscale(my_data):
# my_data is a numerical list or array
my_data= np.asarray(my_data)
m, M = my_data.min(), my_data.max()
if 2 <= m or 2>=M:
raise ValueError('This function works only for data whose range contains 2')
bp = (2-m)/(M-m)    #boundary point in [0,1]; Any normalized value below bp is colored blue, and red above it
return [[0, '#000080'],
[bp, '#000080'],
[bp, '#DC381F'],
[1, '#DC381F']]
``````

Details:

• pass to the function `custom_colorscale()` the list/array of z-values defining the heatmap;
• find the min, `m`, and max, `M`, of these values.
• calculate, `bp`, the image of 2 through the normalization function, i.e. the linear function
`x-->(x-m)/(M-m)`, that maps x in [m, M] to a value in [0,1];
• define the corresponding colorscale.

Example 1:

``````z1 = np.random.randint(0, 4, size=(5,5))
colorscale1 = custom_colorscale(z1)
fig1 = go.Figure(go.Heatmap(z=z1, colorscale=colorscale1))
fig1.update_layout(width=400, height=400)
fig1.show()
``````

Example 2:

``````z2 = np.random.randint(0, 7, size=(7,7))
colorscale2 = custom_colorscale(z2)
fig2 = go.Figure(go.Heatmap(z=z2, colorscale=colorscale2))
fig2.update_layout(width=500, height=500)
fig2.show()
``````