You can get all the individual colorscale name by using the inspect module while iterating over the known color modules:
import inspect
colorscale_names = []
colors_modules = ['carto', 'colorbrewer', 'cmocean', 'cyclical',
'diverging', 'plotlyjs', 'qualitative', 'sequential']
for color_module in colors_modules:
colorscale_names.extend([name for name, body
in inspect.getmembers(getattr(px.colors, color_module))
if isinstance(body, list)])
All the names are now available in the list colorscale_names (including those from PLOTLY_SCALES since they are replicated in the color modules). There are some duplicates, which you could remove by casting it to a set.
Here are all the names printed in columns.
from textwrap import fill
print(fill(''.join(sorted({f'{x: <{15}}' for x in colorscale_names})), 75))
Accent Aggrnyl Agsunset Alphabet Antique
Armyrose Blackbody Bluered Blues Blugrn
Bluyl Bold BrBG Brwnyl BuGn
BuPu Burg Burgyl Cividis D3
Dark2 Dark24 Darkmint Earth Edge
Electric Emrld Fall G10 Geyser
GnBu Greens Greys HSV Hot
IceFire Inferno Jet Light24 Magenta
Magma Mint OrRd Oranges Oryel
PRGn Paired Pastel Pastel1 Pastel2
Peach Phase PiYG Picnic Pinkyl
Plasma Plotly Plotly3 Portland Prism
PuBu PuBuGn PuOr PuRd Purp
Purples Purpor Rainbow RdBu RdGy
RdPu RdYlBu RdYlGn Redor Reds
Safe Set1 Set2 Set3 Spectral
Sunset Sunsetdark T10 Teal Tealgrn
Tealrose Temps Tropic Twilight Viridis
Vivid YlGn YlGnBu YlOrBr YlOrRd
algae amp balance curl deep
delta dense gray haline ice
matter mrybm mygbm oxy phase
scale_pairs scale_sequence solar speed tempo
thermal turbid
Update: there is now a dedicated documentation page for this, including swatches at https://plotly.com/python/builtin-colorscales/
This file contains most of what you’re looking for.
So probably from plotly._plotly_utils.colors import PLOTLY_SCALES will allow you to do colorscales = PLOTLY_SCALES.keys() although this is meant to be an internal object.
I should add that there are other color scales that Plotly will recognize by name but those aren’t available as a neat import like this as they are in other modules like plotly.express.colors.sequential or plotly.express.colors.cyclical etc.
There is a built in method from plotly.express.colors to sample_colorscale which would provide the color samples:
from plotly.express.colors import sample_colorscale
import plotly.graph_objects as go
import numpy as np
x = np.linspace(0, 1, 25)
c = sample_colorscale('jet', list(x))
fig = go.FigureWidget()
fig.add_trace(
go.Bar(x=x, y=y, marker_color=c)
)
fig.show()
See the output figure -> sampled_colors
Plotly does not appear to have such a method, so I wrote one:
import plotly.colors
def get_continuous_color(colorscale, intermed):
"""
Plotly continuous colorscales assign colors to the range [0, 1]. This function computes the intermediate
color for any value in that range.
Plotly doesn't make the colorscales directly accessible in a common format.
Some are ready to use:
colorscale = plotly.colors.PLOTLY_SCALES["Greens"]
Others are just swatches that need to be constructed into a colorscale:
viridis_colors, scale = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)
colorscale = plotly.colors.make_colorscale(viridis_colors, scale=scale)
:param colorscale: A plotly continuous colorscale defined with RGB string colors.
:param intermed: value in the range [0, 1]
:return: color in rgb string format
:rtype: str
"""
if len(colorscale) < 1:
raise ValueError("colorscale must have at least one color")
if intermed <= 0 or len(colorscale) == 1:
return colorscale[0][1]
if intermed >= 1:
return colorscale[-1][1]
for cutoff, color in colorscale:
if intermed > cutoff:
low_cutoff, low_color = cutoff, color
else:
high_cutoff, high_color = cutoff, color
break
# noinspection PyUnboundLocalVariable
return plotly.colors.find_intermediate_color(
lowcolor=low_color, highcolor=high_color,
intermed=((intermed - low_cutoff) / (high_cutoff - low_cutoff)),
colortype="rgb")
The challenge is that the built-in Plotly colorscales are not consistently exposed. Some are defined as a colorscale already, others as just a list of color swatches that must be converted to a color scale first.
The Viridis colorscale is defined with hex values, which the Plotly color manipulation methods don't like, so it's easiest to construct it from swatches like this:
viridis_colors, _ = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)
colorscale = plotly.colors.make_colorscale(viridis_colors)
get_continuous_color(colorscale, intermed=0.25)
# rgb(58.75, 80.75, 138.25)
scattergl trace markers can also have a colorschale. I found a reference for it in the documentation here:
colorscale Parent: data[type=scattergl].marker Type: colorscale Sets the colorscale. Has an effect only if in
marker.coloris set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example,[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]. To control the bounds of the colorscale in color space, usemarker.cminandmarker.cmax. Alternatively,colorscalemay be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,Earth,Electric,Viridis,Cividis.
So an example based on your fiddle you could look like this:
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var trace1 = {
x: x,
y: x,
mode: 'markers',
marker: {
size: 20,
color: x,
colorscale: 'Greens'
},
};
Plotly.newPlot('myDiv', [trace1], {});
Here is an implementation for a custom colorscale based on the viridis colour scale R users will be familiar with.
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var y = vector_normalise(x);
var trace1 = {
x: x,
y: x,
mode: 'markers',
marker: {
colorscale: [
[0.000, "rgb(68, 1, 84)"],
[0.111, "rgb(72, 40, 120)"],
[0.222, "rgb(62, 74, 137)"],
[0.333, "rgb(49, 104, 142)"],
[0.444, "rgb(38, 130, 142)"],
[0.556, "rgb(31, 158, 137)"],
[0.667, "rgb(53, 183, 121)"],
[0.778, "rgb(109, 205, 89)"],
[0.889, "rgb(180, 222, 44)"],
[1.000, "rgb(253, 231, 37)"]
],
color: y,
size: 20,
},
};
Plotly.newPlot('myDiv', [trace1], {});
Below is my normalisation function, I have left it verbose to help with understanding. The input vec could be overwritten and returned to reduce local variables if desired.
function vector_normalise(vec) {
var vmin = Math.min(...vec);
var vmax = Math.max(...vec);
// calculate the delta to save time with big arrays
var vdelta = vmax - vmin;
// create an empty array to return
var vec_ret = [];
// push doesn't seem to like inline functions
var vnorm;
// iterate over the array/vector
vec.forEach(value => {
vnorm = (value - vmin) / vdelta;
vec_ret.push(vnorm);
})
return vec_ret
}
Edit: Turns out Viridis is one of the existing available palettes... 😉
For Plotly.js, the default color list is given in the source code:
'#1f77b4', // muted blue
'#ff7f0e', // safety orange
'#2ca02c', // cooked asparagus green
'#d62728', // brick red
'#9467bd', // muted purple
'#8c564b', // chestnut brown
'#e377c2', // raspberry yogurt pink
'#7f7f7f', // middle gray
'#bcbd22', // curry yellow-green
'#17becf' // blue-teal
For Plotly Python, see this answer.
If a plot has more than 10 series, it will cycle back to the first color.
Plotly uses the same colors as in d3's scale.category10() function. After 10 colors the whole color scheme starts again from 0.
The colors codes can be found in KDD's answer. The snippet below gives the d3 colors and takes the Plotly colors dynamically from a plot, i.e. even if the Plotly changes the color codes will be correct.
var d3colors = Plotly.d3.scale.category10();
var color_div = document.getElementById('colors');
var data = [];
for (var i = 0; i < 11; i += 1) {
data.push({
x: [i],
y: [i + 1],
name: i + ": Color: " + d3colors(i),
type: 'bar'
});
}
Plotly.plot('colors', data);
var node;
var textnode;
for (var i = 0; i < 10; i += 1) {
var color = d3colors(i);
node = document.createElement("div");
node.style.color = color;
var text = "D3: " + color;
textnode = document.createTextNode(text);
node.appendChild(textnode);
node.appendChild(document.createElement("br"));
var rgb = Plotly.d3.selectAll('.point').selectAll('path')[i][0].style.fill;
color = Plotly.d3.rgb(rgb).toString()
var text = "Plotly: " + color + " ; " + rgb;
textnode = document.createTextNode(text);
node.appendChild(textnode);
color_div.appendChild(node);
}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="colors"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand