@AnnMarieW , @TallTim Yes this a 8 years old version of asymmetric colorscale :grinning: Here is a much shorter one from matplotlib.colors import to_hex import numpy as np def asymmetric_cmap(cmap, vmin, vmax, ncolors=11): v_max_abs=max([abs(vmin), abs(vmax)]) arr_colors=cmap(np.linspace… Answer from empet on community.plotly.com
🌐
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.
🌐
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.
🌐
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 › 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: 'YlOrRd', type: 'heatmap' } ]; var layout = { title: { text: 'YlOrRd' } }; Plotly.newPlot('myDiv', data, layout); });
🌐
Plotly
plotly.com › r › colorscales
Colorscales | R | Plotly
To share colorscale information in multiple subplots, you can use coloraxis. Below we show how to set a reference coloraxis1 to a shared coloraxis, which are set in the layout. Note that multiple color scales can be linked to the same color. library(plotly) fig1 <- plot_ly( type = "heatmap", x = c(1,2,3,4), z = list(c(1,2,3,4), c(4,-3,-1,1)), coloraxis = 'coloraxis') fig2 <- plot_ly( type = "heatmap", x = c(3,4,5,6), z = list(c(10,2,1,0), c(4,3,5,6)), coloraxis = 'coloraxis') fig <- subplot(fig1, fig2) fig <- fig %>% layout(coloraxis=list(colorscale='Jet')) fig
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
community.plotly.com › 📊 plotly python
Colors for discrete ranges in heatmaps - 📊 Plotly Python - Plotly Community Forum
January 17, 2018 - 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/ but rather than discrete bars, the heatmap has a range of colors. Here is the script I am using: def ...
🌐
Plotly
plotly.com › r › heatmaps
Heatmaps in R
fig <- plot_ly(z = volcano, colors = colorRamp(c("red", "green")), type = "heatmap") fig · Or, you can do the scaling yourself and use the colorscale attribute directly...
🌐
Plotly
plotly.com › python › heatmaps
Heatmaps in Python
Over 11 examples of Heatmaps including changing color, size, log axes, and more in Python.
Find elsewhere
🌐
Plotly
plotly.com › fsharp › logarithmic-color-scale
Continuous Color Scales and Color Bars | Fsharp | Plotly
let z = data.Z //let customColorscale = StyleParam.Colorscale.Custom [(0.0,"#A6CEE3");(1.0,"#E31A1C")] let customColorscale = StyleParam.Colorscale.Custom [(0.0,"rgb(165,0,38)"); (0.11,"rgb(215,48,39)"); (0.22,"rgb(244,109,67)"); (0.33,"rgb(253,174,97)"); (0.44,"rgb(254,224,144)"); (0.55,"rgb(224,243,248)"); (0.66,"rgb(171,217,233)"); (0.77,"rgb(116,173,209)"); (0.88,"rgb(69,117,180)"); (1.0,"rgb(49,54,149)");] ... Chart.Heatmap(z, Colorscale=customColorscale, Colorbar= Colorbar.init(Title="Surface Heat",Titleside=StyleParam.Side.Top, Tickmode=StyleParam.TickMode.Array, Tickvals=[|2;50;100|],Ticktext=[|"Cool";"Mild";"Hot"|]))
🌐
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).
🌐
Educative
educative.io › answers › how-to-create-a-heatmap-plot-with-plotly-graph-objects-in-python
How to create a heatmap plot with Plotly Graph Objects in Python
colorscale (optional): This specifies the color scale used to map values to colors in the heatmap. Plotly provides a variety of predefined color scales, such as 'Viridis', 'YlOrRd', 'Blues', etc.
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)

🌐
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 ·
🌐
Plotly
plotly.com › javascript › heatmaps
Heatmaps in JavaScript
var data = [ { z: [[1, null, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]], x: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], y: ['Morning', 'Afternoon', 'Evening'], type: 'heatmap', hoverongaps: false } ]; Plotly.newPlot('myDiv', data); var xValues = ['A', 'B', 'C', 'D', 'E']; var yValues = ['W', 'X', 'Y', 'Z']; var zValues = [ [0.00, 0.00, 0.75, 0.75, 0.00], [0.00, 0.00, 0.75, 0.75, 0.00], [0.75, 0.75, 0.75, 0.75, 0.75], [0.00, 0.00, 0.00, 0.75, 0.00] ]; var colorscaleValue = [ [0, '#3D9970'], [1, '#001f3f'] ]; var data = [{ x: xValues, y: yValues, z: zValues, type: 'heat
🌐
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 ...
🌐
Plotly
plotly.com › javascript › reference › heatmap
JavaScript Figure Reference: heatmap Traces
"paper" refers to the height of the plotting area only. autocolorscale Parent: data[type=heatmap] Type: boolean · Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed.
🌐
Stack Overflow
stackoverflow.com › questions › 60175461 › custom-color-scales-on-heatmap
python - Custom color scales on heatmap - Stack Overflow
I have tried seaborn heatmap but not able to set the conditioned custom color scale. Any clue would be greatly appreciated. Thanks! ... See this post about how to build a colormap with associated boundarynorm. The post is for 2 colors, more colors just means adding to the list of colors and of boundaries. ... Save this answer. ... Show activity on this post. since you tagged plotly, you can find an example on how to create a custom colorscale here https://plot.ly/python/colorscales/#constructing-a-discrete-or-discontinuous-color-scale - but reading through the whole page is useful (and the heatmap tutorial is here https://plot.ly/python/heatmaps/).