0
# Color Utilities
1
2
Comprehensive color management with built-in color scales, palette generation, and color format conversion. The colors module supports sequential, diverging, cyclical, and qualitative color schemes with over 50 utility functions.
3
4
## Capabilities
5
6
### Color Format Conversion
7
8
Functions for converting between different color representation formats.
9
10
```python { .api }
11
def hex_to_rgb(hex_color):
12
"""
13
Convert hex color to RGB tuple.
14
15
Parameters:
16
- hex_color: str, hex color string (e.g., '#FF0000' or 'FF0000')
17
18
Returns:
19
tuple: RGB values as (r, g, b) where each value is 0-255
20
"""
21
22
def rgb_to_hex(rgb_tuple):
23
"""
24
Convert RGB tuple to hex color string.
25
26
Parameters:
27
- rgb_tuple: tuple, RGB values as (r, g, b) where each value is 0-255
28
29
Returns:
30
str: Hex color string with leading '#'
31
"""
32
33
def convert_colors_to_same_type(colors, colortype='tuple'):
34
"""
35
Convert list of colors to same format type.
36
37
Parameters:
38
- colors: list, colors in various formats (hex, rgb, named)
39
- colortype: str, target format ('tuple', 'hex')
40
41
Returns:
42
list: Colors converted to specified format
43
"""
44
45
def convert_to_RGB_255(colors):
46
"""
47
Convert colors to RGB 255 format.
48
49
Parameters:
50
- colors: list, colors in various formats
51
52
Returns:
53
list: Colors as RGB tuples with values 0-255
54
"""
55
56
def unconvert_from_RGB_255(colors):
57
"""
58
Convert colors from RGB 255 format to normalized RGB.
59
60
Parameters:
61
- colors: list, RGB colors with values 0-255
62
63
Returns:
64
list: Colors as normalized RGB tuples with values 0-1
65
"""
66
67
def label_rgb(colors):
68
"""
69
Add 'rgb' labels to RGB color tuples.
70
71
Parameters:
72
- colors: list, RGB color tuples
73
74
Returns:
75
list: RGB colors formatted as 'rgb(r, g, b)' strings
76
"""
77
78
def unlabel_rgb(colors):
79
"""
80
Remove 'rgb' labels from RGB color strings.
81
82
Parameters:
83
- colors: list, RGB color strings like 'rgb(r, g, b)'
84
85
Returns:
86
list: RGB colors as tuples (r, g, b)
87
"""
88
```
89
90
### Color Scale Creation and Manipulation
91
92
Functions for creating custom color scales and sampling from existing ones.
93
94
```python { .api }
95
def make_colorscale(colors, position=None):
96
"""
97
Create a custom color scale from color list.
98
99
Parameters:
100
- colors: list, colors for the scale (hex, rgb, or named)
101
- position: list, optional positions (0-1) for each color
102
103
Returns:
104
list: Color scale as list of [position, color] pairs
105
"""
106
107
def sample_colorscale(colorscale, samplepoints, low=0.0, high=1.0,
108
colortype='tuple'):
109
"""
110
Sample colors from a color scale at specified points.
111
112
Parameters:
113
- colorscale: str or list, color scale name or custom scale
114
- samplepoints: list, positions (0-1) to sample from scale
115
- low: float, lower bound for sampling range
116
- high: float, upper bound for sampling range
117
- colortype: str, output format ('tuple', 'hex')
118
119
Returns:
120
list: Sampled colors in specified format
121
"""
122
123
def find_intermediate_color(lowcolor, highcolor, intermed, colortype='tuple'):
124
"""
125
Find intermediate color between two colors.
126
127
Parameters:
128
- lowcolor: str or tuple, starting color
129
- highcolor: str or tuple, ending color
130
- intermed: float, interpolation factor (0-1)
131
- colortype: str, output format ('tuple', 'hex')
132
133
Returns:
134
str or tuple: Intermediate color in specified format
135
"""
136
137
def get_colorscale(name):
138
"""
139
Get built-in color scale by name.
140
141
Parameters:
142
- name: str, color scale name
143
144
Returns:
145
list: Color scale as list of [position, color] pairs
146
"""
147
```
148
149
### Color Validation and Parsing
150
151
Functions for validating and parsing color specifications.
152
153
```python { .api }
154
def validate_colors(colors, colortype='tuple'):
155
"""
156
Validate that colors are in correct format.
157
158
Parameters:
159
- colors: list, colors to validate
160
- colortype: str, expected format ('tuple', 'hex')
161
162
Returns:
163
bool: True if all colors are valid
164
165
Raises:
166
PlotlyError: If colors are invalid
167
"""
168
169
def color_parser(colors, function):
170
"""
171
Parse and process colors through a function.
172
173
Parameters:
174
- colors: list, input colors in various formats
175
- function: str, processing function name
176
177
Returns:
178
list: Processed colors
179
"""
180
181
def validate_colorscale(colorscale):
182
"""
183
Validate that colorscale is properly formatted.
184
185
Parameters:
186
- colorscale: list, color scale to validate
187
188
Returns:
189
bool: True if colorscale is valid
190
191
Raises:
192
PlotlyError: If colorscale is invalid
193
"""
194
```
195
196
### Built-in Color Scales
197
198
Color scale namespaces containing predefined color schemes for different data types.
199
200
```python { .api }
201
# Sequential color scales - for continuous data with natural ordering
202
sequential = ColorScaleNamespace([
203
'Viridis', 'Plasma', 'Inferno', 'Magma', 'Cividis',
204
'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys',
205
'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples',
206
'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
207
'Hot', 'Jet', 'Blackbody', 'Earth', 'Electric', 'Rainbow',
208
'Portland', 'Blackbody', 'Earth', 'Electric', 'Viridis_r',
209
'Plasma_r', 'Inferno_r', 'Magma_r', 'Cividis_r'
210
])
211
212
# Diverging color scales - for data with meaningful center point
213
diverging = ColorScaleNamespace([
214
'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'BrBG', 'PiYG',
215
'PRGn', 'PuOr', 'RdGy', 'Tealrose', 'Temps', 'Tropic',
216
'Balance', 'HSV', 'Picnic', 'Portland', 'RdBu_r',
217
'RdYlBu_r', 'RdYlGn_r', 'Spectral_r'
218
])
219
220
# Cyclical color scales - for periodic/circular data
221
cyclical = ColorScaleNamespace([
222
'IceFire', 'Edge', 'HSV', 'mrybm', 'mygbm', 'Phase',
223
'IceFire_r', 'Edge_r', 'HSV_r', 'mrybm_r', 'mygbm_r'
224
])
225
226
# Qualitative color scales - for categorical data
227
qualitative = ColorScaleNamespace([
228
'Set1', 'Set2', 'Set3', 'Pastel1', 'Pastel2', 'Dark2',
229
'Accent', 'Alphabet', 'Antique', 'Bold', 'Light24',
230
'Plotly', 'Prism', 'Safe', 'Vivid', 'D3', 'G10', 'T10'
231
])
232
233
# Access individual scales
234
sequential.Viridis: list # Viridis color scale
235
diverging.RdBu: list # Red-Blue diverging scale
236
cyclical.IceFire: list # Ice-Fire cyclical scale
237
qualitative.Set1: list # Set1 qualitative colors
238
```
239
240
### Color Scale Utilities
241
242
Additional utilities for working with color scales and palettes.
243
244
```python { .api }
245
def n_colors(lowcolor, highcolor, n_colors, colortype='tuple'):
246
"""
247
Generate n evenly spaced colors between two colors.
248
249
Parameters:
250
- lowcolor: str or tuple, starting color
251
- highcolor: str or tuple, ending color
252
- n_colors: int, number of colors to generate
253
- colortype: str, output format ('tuple', 'hex')
254
255
Returns:
256
list: List of n interpolated colors
257
"""
258
259
def colorscale_to_colors(colorscale, n_colors=None):
260
"""
261
Extract color list from color scale.
262
263
Parameters:
264
- colorscale: str or list, color scale name or definition
265
- n_colors: int, number of colors to extract (default: all)
266
267
Returns:
268
list: Colors from the color scale
269
"""
270
271
def colors_to_colorscale(colors):
272
"""
273
Convert color list to color scale format.
274
275
Parameters:
276
- colors: list, colors to convert
277
278
Returns:
279
list: Color scale as [position, color] pairs
280
"""
281
282
def get_colorscale_names():
283
"""
284
Get all available built-in color scale names.
285
286
Returns:
287
dict: Color scale names grouped by type
288
- 'sequential': list of sequential scale names
289
- 'diverging': list of diverging scale names
290
- 'cyclical': list of cyclical scale names
291
- 'qualitative': list of qualitative scale names
292
"""
293
294
def swatches(colorscale=None, colors=None, template=None):
295
"""
296
Create color swatch visualization.
297
298
Parameters:
299
- colorscale: str or list, color scale to visualize
300
- colors: list, individual colors to visualize
301
- template: str, plotly template for styling
302
303
Returns:
304
Figure: Plotly figure showing color swatches
305
"""
306
```
307
308
### Named Colors
309
310
Access to standard named colors and CSS color names.
311
312
```python { .api }
313
# Named color constants
314
PLOTLY_COLORS: list # Default plotly color sequence
315
DEFAULT_PLOTLY_COLORS: list # Legacy default colors
316
317
# CSS named colors (subset)
318
CSS_NAMED_COLORS = {
319
'aliceblue': '#F0F8FF',
320
'antiquewhite': '#FAEBD7',
321
'aqua': '#00FFFF',
322
'aquamarine': '#7FFFD4',
323
'azure': '#F0FFFF',
324
'beige': '#F5F5DC',
325
'bisque': '#FFE4C4',
326
'black': '#000000',
327
'blue': '#0000FF',
328
'brown': '#A52A2A',
329
'cyan': '#00FFFF',
330
'gold': '#FFD700',
331
'green': '#008000',
332
'grey': '#808080',
333
'magenta': '#FF00FF',
334
'orange': '#FFA500',
335
'pink': '#FFC0CB',
336
'purple': '#800080',
337
'red': '#FF0000',
338
'white': '#FFFFFF',
339
'yellow': '#FFFF00'
340
# ... and many more
341
}
342
```
343
344
## Usage Examples
345
346
```python
347
import plotly.colors as pc
348
import plotly.express as px
349
import numpy as np
350
351
# Color format conversion
352
hex_color = '#FF5733'
353
rgb_tuple = pc.hex_to_rgb(hex_color) # (255, 87, 51)
354
hex_back = pc.rgb_to_hex(rgb_tuple) # '#FF5733'
355
356
# Create custom color scale
357
custom_colors = ['red', 'yellow', 'green', 'blue']
358
custom_scale = pc.make_colorscale(custom_colors)
359
360
# Sample colors from built-in scale
361
viridis_samples = pc.sample_colorscale('Viridis', [0, 0.25, 0.5, 0.75, 1.0])
362
363
# Find intermediate color
364
intermediate = pc.find_intermediate_color('red', 'blue', 0.5) # Purple
365
366
# Generate color gradient
367
gradient = pc.n_colors('lightblue', 'darkblue', 10)
368
369
# Use color scales in plots
370
df = px.data.tips()
371
372
# Sequential scale for continuous data
373
fig1 = px.scatter(df, x="total_bill", y="tip", color="size",
374
color_continuous_scale=pc.sequential.Viridis)
375
376
# Diverging scale for data with meaningful center
377
fig2 = px.imshow(np.random.randn(20, 20),
378
color_continuous_scale=pc.diverging.RdBu)
379
380
# Qualitative colors for categories
381
fig3 = px.scatter(df, x="total_bill", y="tip", color="day",
382
color_discrete_sequence=pc.qualitative.Set1)
383
384
# Custom colorscale
385
fig4 = px.scatter(df, x="total_bill", y="tip", color="size",
386
color_continuous_scale=custom_scale)
387
388
# Color swatch visualization
389
swatch_fig = pc.swatches('Viridis')
390
swatch_fig.show()
391
392
# List available color scales
393
scale_names = pc.get_colorscale_names()
394
print("Sequential:", scale_names['sequential'][:5])
395
print("Diverging:", scale_names['diverging'][:5])
396
print("Qualitative:", scale_names['qualitative'][:5])
397
398
# Validate colors
399
colors_to_check = ['red', '#FF0000', (255, 0, 0)]
400
is_valid = pc.validate_colors(colors_to_check, colortype='tuple')
401
402
# Access color scale data directly
403
viridis_scale = pc.sequential.Viridis
404
print(f"Viridis has {len(viridis_scale)} color stops")
405
406
# Extract colors from scale
407
viridis_colors = pc.colorscale_to_colors('Viridis', n_colors=5)
408
409
# Convert colors to scale format
410
my_colors = ['red', 'orange', 'yellow', 'green', 'blue']
411
my_scale = pc.colors_to_colorscale(my_colors)
412
```