There may be more elegant ways. But the following suggestion sets up buttons with args for all colors available to go.Heatmap() by default by building one figure for every colorscale, "stealing" those colorscales one by one, and then making them available as updates to your figure throgh:

# buttons, temporary figures and colorscales
for i, scale in enumerate(scales):
    colors.append(go.Figure(data=go.Heatmap(z=z,colorscale = scale)).data[0].colorscale)
    buttons.append(dict(method='restyle',
                        label=scale,
                        visible=True,
                        args=[{'colorscale':[colors[i]],
                                }, ],
                        )
                  )

Figure with update button:

Some details about the solution:

So why the hassle with colors.append(go.Figure(data=go.Heatmap(z=z,colorscale = scale)).data[0].colorscale)? As I said, there might be more elegant ways. But this approach at least ensures that the colorscales keep the same sructure for all colors in:

(Heatmap({
     'colorscale': [[0.0, 'rgb(237, 229, 207)'], [0.16666666666666666, 'rgb(224,
                    194, 162)'], [0.3333333333333333, 'rgb(211, 156, 131)'], [0.5,
                    'rgb(193, 118, 111)'], [0.6666666666666666, 'rgb(166, 84, 97)'],
                    [0.8333333333333334, 'rgb(129, 55, 83)'], [1.0, 'rgb(84, 31,
                    63)']],
     'z': [[1, 20, 30], [20, 1, 60], [30, 60, 1]]
 }),)

Which is the structure you're editing through buttons and updatemenu.

Complete code:

# imports 
import plotly.graph_objects as go

# data
z=[[1, 20, 30],
  [20, 1, 60],
  [30, 60, 1]]

# every colorscale available to go.Heatmap() by default
scales =     ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
             'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
             'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
             'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
             'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
             'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
             'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
             'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg',
             'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor',
             'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy',
             'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral',
             'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose',
             'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight',
             'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']

# scales = scales[10:13]
colors =[]
buttons = []

# buttons, temporary figures and colorscales
for i, scale in enumerate(scales):
    colors.append(go.Figure(data=go.Heatmap(z=z,colorscale = scale)).data[0].colorscale)
    buttons.append(dict(method='restyle',
                        label=scale,
                        visible=True,
                        args=[{'colorscale':[colors[i]],
                                }, ],
                        )
                  )

# Initial figure:
fig = go.Figure(data=go.Heatmap(z=z, colorscale = scales[0]))

# some adjustments to the updatemenus
updatemenu = []
your_menu = dict()
updatemenu.append(your_menu)
updatemenu[0]['buttons'] = buttons
fig.update_layout(showlegend=False, updatemenus=updatemenu)

# f = fig.
fig.show()
Answer from vestland on Stack Overflow
🌐
Plotly
plotly.github.io › plotly.py-docs › generated › plotly.graph_objects.Heatmap.html
plotly.graph_objects.Heatmap — 7.0.0 documentation
colorbar – plotly.graph_objects.heatmap.ColorBar instance or dict with compatible properties · colorscale – Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsla, hwb, or named color string.
🌐
Plotly
plotly.com › python › colorscales
Continuous color scales and color bars in Python
Color scale defaults depend on the layout.colorscales attributes of the active template, and can be explicitly specified using the color_continuous_scale argument for many Plotly Express functions or the colorscale argument in various graph_objects such as layout.coloraxis or marker.colorscale in go.Scatter traces or colorscale in go.Heatmap traces.
Top answer
1 of 1
1

There may be more elegant ways. But the following suggestion sets up buttons with args for all colors available to go.Heatmap() by default by building one figure for every colorscale, "stealing" those colorscales one by one, and then making them available as updates to your figure throgh:

# buttons, temporary figures and colorscales
for i, scale in enumerate(scales):
    colors.append(go.Figure(data=go.Heatmap(z=z,colorscale = scale)).data[0].colorscale)
    buttons.append(dict(method='restyle',
                        label=scale,
                        visible=True,
                        args=[{'colorscale':[colors[i]],
                                }, ],
                        )
                  )

Figure with update button:

Some details about the solution:

So why the hassle with colors.append(go.Figure(data=go.Heatmap(z=z,colorscale = scale)).data[0].colorscale)? As I said, there might be more elegant ways. But this approach at least ensures that the colorscales keep the same sructure for all colors in:

(Heatmap({
     'colorscale': [[0.0, 'rgb(237, 229, 207)'], [0.16666666666666666, 'rgb(224,
                    194, 162)'], [0.3333333333333333, 'rgb(211, 156, 131)'], [0.5,
                    'rgb(193, 118, 111)'], [0.6666666666666666, 'rgb(166, 84, 97)'],
                    [0.8333333333333334, 'rgb(129, 55, 83)'], [1.0, 'rgb(84, 31,
                    63)']],
     'z': [[1, 20, 30], [20, 1, 60], [30, 60, 1]]
 }),)

Which is the structure you're editing through buttons and updatemenu.

Complete code:

# imports 
import plotly.graph_objects as go

# data
z=[[1, 20, 30],
  [20, 1, 60],
  [30, 60, 1]]

# every colorscale available to go.Heatmap() by default
scales =     ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
             'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
             'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
             'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
             'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
             'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
             'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
             'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg',
             'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor',
             'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy',
             'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral',
             'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose',
             'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight',
             'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']

# scales = scales[10:13]
colors =[]
buttons = []

# buttons, temporary figures and colorscales
for i, scale in enumerate(scales):
    colors.append(go.Figure(data=go.Heatmap(z=z,colorscale = scale)).data[0].colorscale)
    buttons.append(dict(method='restyle',
                        label=scale,
                        visible=True,
                        args=[{'colorscale':[colors[i]],
                                }, ],
                        )
                  )

# Initial figure:
fig = go.Figure(data=go.Heatmap(z=z, colorscale = scales[0]))

# some adjustments to the updatemenus
updatemenu = []
your_menu = dict()
updatemenu.append(your_menu)
updatemenu[0]['buttons'] = buttons
fig.update_layout(showlegend=False, updatemenus=updatemenu)

# f = fig.
fig.show()
🌐
Plotly
plotly.com › javascript › colorscales
Colorscales in JavaScript
d3.json('https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json', function(figure) { var data = [{ z: figure.z, colorscale: 'YlGnBu', type: 'heatmap' } ]; var layout = { title: { text: 'YlGnBu' } }; Plotly.newPlot('myDiv', data, layout); });
🌐
Plotly
community.plotly.com › dash python
Dash Newbie - Heatmap Custom Color Scales Per Column - Dash Python - Plotly Community Forum
April 30, 2023 - Hello, found this forum from the book “The Book Of Dash” and I’m hopeful someone can assist me on this problem. I’ve managed to stumble through a few examples and create my own annotated heatmap, reading in data from .csv files and all, but I don’t like the built-in colorscale.
🌐
PYTHON CHARTS
python-charts.com › home › correlation › heatmaps in plotly with imshow
Heatmaps in plotly with imshow | PYTHON CHARTS
October 23, 2022 - The default color palette of the plotly heatmaps can be overriden through the color_continuous_scale argument. Recall that you can see the full list of available palettes with px.colors.named_colorscales() after importing the plotly express module.
🌐
Plotly
community.plotly.com › 📊 plotly python
Colors for discrete ranges in heatmaps - 📊 Plotly Python - Plotly Community Forum
January 17, 2018 - I’m trying to make a heatmap using different colors for discreet ranges of data, using Plotly in python/pandas. My colleague sent me an image of the color ranges she would like used for the data. I used the “Custom Discretized Heatmap Colorscale” example at https://plot.ly/python/colorscales/ ...
Find elsewhere
🌐
Plotly
plotly.com › python › heatmaps
Heatmaps in Python
Over 11 examples of Heatmaps including changing color, size, log axes, and more in Python.
Top answer
1 of 1
12

The code you use to generate a color palette works just fine. You only need to provide data that match with a heatmap. The following code provides this:

library(RColorBrewer)
library(plotly)

# your palette definition
palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                              "green","yellow", "red", "darkred"))

set.seed(9876)    # for reproducibility

## a complete random set
hmdata <- matrix(data = sample(x = 1:10^6, size = 100*100), nrow = 100, ncol = 100)
plot_ly(z = hmdata, colors = palette(50), type = "heatmap")

This gives the following heatmap:

## a random set that has been sorted
hmdata_s <- matrix(data = sort(sample(x = 1:10^6, size = 100*100)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s, colors = palette(50), type = "heatmap")

Yielding this plot:

Please let me know whether this is what you want.

UPDATE

you can set custom scale in plot_ly with zauto, zmax, and zmin. The following 2 pieces of code and graphs will illustrate this:

The scale is set from 1 to 100 and the data vary similarly:

hmdata_s3 <- matrix(data = sort(sample(x = 1:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s3, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)

The scale is set from 1 to 100 and the data vary between 50 and 100 only

hmdata_s4 <- matrix(data = sort(sample(x = 50:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s4, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)

🌐
Plotly
community.plotly.com › dash python
Plotly Annotated Heatmap Colorscale (DASH) - Dash Python - Plotly Community Forum
July 10, 2020 - import numpy as np np.random.seed(1) z = np.random.randint(low=-20, high=100, size=(10, 10)) # get a flattened array of all of the z values, sorted z_flat = np.sort(z, axis=None) # find how many negative numers are in the array negative_numbers = np.sum(np.array(z_flat) <= 0, axis=0) # normalize array between 0 and 1 for the color scale def normalize(x): return (x - np.min(x)) / (np.max(x) - np.min(x)) normalized_scale = normalize(z_flat) # find the point in the normalized scale where the numbers change from neg to positive border1 = normalized_scale[negative_numbers] # set the second border t
🌐
Stack Overflow
stackoverflow.com › questions › 73809207 › plotly-heat-map-color-scale
reactjs - Plotly Heat Map Color Scale - Stack Overflow
<Plot data={[{ x, y, z, colorscale: [ [0, 'rgba(254, 73, 44, 0.9)'], [0.5, 'rgba(255, 208, 0, 0.9)'], [1, 'rgba(97, 201, 164, 0.9)'] ], zmax: 12, zmin: 0, zauto: false, zsmooth: 'best', type: attributes.showLines !== undefined ? attributes.showLines ? 'contour' : 'heatmap' : 'heatmap', showscale: false, connectgaps: true, zAxis: { domain: [0, 20] } } ]} layout={{ title: null, autosize: true, autosize: true, yaxis: { autorange: 'reversed' }, zaxis: { zmin: 0, zmax: 15, zauto: false, }, xaxis: { type: 'date' }, }} useResizeHandler={true} style={{ width: "100%", height: "100%" }} />
🌐
Stack Overflow
stackoverflow.com › questions › 60534820 › using-plotly-create-a-heatmap-changing-colors
r - Using Plotly create a heatmap; changing colors - Stack Overflow
fig <- plot_ly( x = c("EMD", "O&S", "P&D"), y = c("Overall Assessment", "Budget Equals Estimate", "Risk Assessment (Cost Schedule Technical)", "Crosschecks", "Cost & Methodology", "Schedule Baseline", "Engineering Technical Baseline", "Requirements Definition"), z = m, colorscale = "YlOrRd", type = "heatmap") %>% layout(xaxis = list(side = "top"), yaxis = list(categoryorder = "trace", title = "Confidence Enablers"), margin = list(l=10, r=10, b=10, t=10))
🌐
Plotly
community.plotly.com › dash python
Scaled Colorscale for heatmap (python) - Dash Python - Plotly Community Forum
November 2, 2018 - I have a situation where I am tracking historical returns (dynamically), and if negative, I want all colors to be red, (different shades of red depending on how much negative it is), and if positive, I want all colors to be green (also depending on how much bigger than zero).
🌐
Plotly
community.plotly.com › plotly.js
How do I change colors in heatmap? - plotly.js - Plotly Community Forum
September 21, 2016 - I am trying to create heatmap. How do I change colors?
🌐
Stack Overflow
stackoverflow.com › questions › 73509956 › how-to-change-the-colours-in-plotly-heatmap
python - How to change the colours in plotly heatmap - Stack Overflow
I am trying to use plotly to plot heatmap but with specific colours based on some values. Based on the dataframe. if the value is less than 0.05, I want the cell to be green if the cell is greater than 0.05 but less than 0.1, I want the colour to be green. The conditional statement will look like something below: colorscales = [] data_mask = df_mask.to_numpy() for row in data_mask: for value in row: if np.isnan(value): color = "#f8fffa" elif float(value) < 0.05: color = "#10c13b" elif (float(value) > 0.05) and (float(value) < 0.1): color = '#fac511' colorscales.append(color)
🌐
R Graph Gallery
r-graph-gallery.com › 215-interactive-heatmap-with-plotly.html
Plotly heatmap – the R Graph Gallery
# Load the plotly package library(plotly) # Data: mtcars: data <- as.matrix(mtcars) # Normalize data data <- apply(data, 2, function(x){x/mean(x)}) # Heatmap p <- plot_ly(x=colnames(data), y=rownames(data), z = data, type = "heatmap", colorscale= "Earth", showscale = F) %>% layout(margin = list(l=120)) p # save the widget # library(htmlwidgets) # saveWidget(p, file=paste0( getwd(), "/HtmlWidget/plotlyHeatmap2.html")) Related chart types ·
🌐
GitHub
github.com › plotly › plotly.py › issues › 3041
[Bug] Zmax and Zmin parameters in Go.Heatmap() are not working · Issue #3041 · plotly/plotly.py
January 22, 2021 - According to the plotly.graph_object.Heatmap documentation, you can set the max and min of the colorscale by using the parameters zmin and zmax - https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.Heatmap.html.
Author: plotly
🌐
Julia Programming Language
discourse.julialang.org › new to julia
PlotlyJS Heatmap change colors to grayscale - New to Julia - Julia Programming Language
November 9, 2022 - I want to transform my thermal heatmap to grayscale. I tried different options and arguments, though it keeps returning the standard color format. I’m using the packages below with versions and ran the attached code below to test it on random. using PlotlyJS, Plots, Distributions, Statistics, ColorSchemes test_x=vec(collect(1:2:30)) test_y=vec(collect(1:10)) rand_test = Matrix(rand(10, 15)) PlotlyJS.plot(PlotlyJS.heatmap(x=test_x, y=test_y, z=rand_test, seriescolor=cgrad(:grayC))) # Though jus...