sc_colors
Handle colors and colormaps.
Highlights
- Adds colormaps including
'turbo','parula', and'orangeblue' sc.hex2rgb()/sc.rgb2hex(): convert between different color conventionssc.vectocolor(): map a list of sequential values onto a list of colorssc.gridcolors(): map a list of qualitative categories onto a list of colors
Functions
| Name | Description |
|---|---|
| alpinecolormap | This function generates a map based on ascending height. Based on data from |
| arraycolors | Map an N-dimensional array of values onto the current colormap. An extension |
| bandedcolormap | Map colors onto bands of hue and saturation, with lightness mapped linearly. |
| bicolormap | This function generators a two-color map, blue for negative, red for |
| colormapdemo | Demonstrate a color map using simulated elevation data, shown in both 2D and |
| gridcolors | Create a qualitative “color map” by assigning points according to the maximum |
| hex2rgb | A little helper function to convert e.g. ‘87bc26’ to a pleasing shade of green. |
| hsv2rgb | Shortcut to Matplotlib’s hsv_to_rgb method, accepts a color triplet or a list/array of color triplets. |
| manualcolorbar | Add a colorbar to a plot that does not support one by default. |
| midpointnorm | Alias to Matplotlib’s TwoSlopeNorm. Used to place the center of the colormap |
| orangebluecolormap | Create an orange-blue colormap; most like RdYlBu but more pleasing. Created |
| parulacolormap | Create a map similar to Viridis, but brighter. Set apply=True to use |
| rgb2hex | A little helper function to convert e.g. [0.53, 0.74, 0.15] to a pleasing shade of green. |
| rgb2hsv | Shortcut to Matplotlib’s rgb_to_hsv method, accepts a color triplet or a list/array of color triplets. |
| sanitizecolor | Alias to matplotlib.colors.to_rgb, but also handles numeric inputs. |
| shifthue | Shift the hue of the colors being fed in. |
| turbocolormap | NOTE: as of Matplotlib 3.4.0, this colormap is included by default, and will |
| vectocolor | This function converts a vector (i.e., 1D array) of N values into an Nx3 matrix |
alpinecolormap
sc_colors.alpinecolormap(apply=False)This function generates a map based on ascending height. Based on data from Kazakhstan.
Test case:
sc.colormapdemo('alpine')Usage example:
import sciris as sc
import matplotlib.pyplot as plt
plt.imshow(np.random.randn(20,20), interpolation='none', cmap=sc.alpinecolormap())Version: 2014aug06
arraycolors
sc_colors.arraycolors(arr, **kwargs)Map an N-dimensional array of values onto the current colormap. An extension of vectocolor() for multidimensional arrays; see that function for additional arguments.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| arr | array | a multidimensional array to be converted to an array of colors | required |
| kwargs | dict | passed to sc.vectocolor() |
{} |
Example:
n = 1000
ncols = 5
arr = np.random.rand(n,ncols)
for c in range(ncols):
arr[:,c] += c
x = np.random.rand(n)
y = np.random.rand(n)
colors = sc.arraycolors(arr)
plt.figure(figsize=(20,16))
for c in range(ncols):
plt.scatter(x+c, y, s=50, c=colors[:,c])Version: 2020mar07
- New in version 3.1.0: Handle non-array output
bandedcolormap
sc_colors.bandedcolormap(
minvalue=None,
minsaturation=None,
hueshift=None,
saturationscale=None,
npts=None,
apply=False,
)Map colors onto bands of hue and saturation, with lightness mapped linearly. Unlike most colormaps, this colormap does not aim to be percentually uniform, but rather aims to make it easy to relate colors to as-exact-as-possible numbers (while still maintaining a semblance of overall trend from low to high).
Demo and example:
cmap = sc.bandedcolormap(minvalue=0, minsaturation=0)
sc.colormapdemo(cmap=cmap)Version: 2019aug22
bicolormap
sc_colors.bicolormap(
gap=0.1,
mingreen=0.2,
redbluemix=0.5,
epsilon=0.01,
demo=False,
apply=False,
)This function generators a two-color map, blue for negative, red for positive changes, with grey in the middle. The input argument is how much of a color gap there is between the red scale and the blue one.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| gap | float | sets how big of a gap between red and blue color scales there is (0=no gap; 1=pure red and pure blue) | 0.1 |
| mingreen | float | how much green to include at the extremes of the red-blue color scale | 0.2 |
| redbluemix | float | how much red to mix with the blue and vice versa at the extremes of the scale | 0.5 |
| epsilon | float | what fraction of the colormap to make gray in the middle | 0.01 |
| demo | bool | whether to plot a demo bicolormap or not | False |
| apply | bool | whether to apply this colormap to the current figure | False |
Examples:
sc.bicolormap(gap=0, mingreen=0, redbluemix=1, epsilon=0) # From pure red to pure blue with white in the middle
sc.bicolormap(gap=0, mingreen=0, redbluemix=0, epsilon=0.1) # Red -> yellow -> gray -> turquoise -> blue
sc.bicolormap(gap=0.3, mingreen=0.2, redbluemix=0, epsilon=0.01) # Red and blue with a sharp distinction betweenVersion: 2013sep13
colormapdemo
sc_colors.colormapdemo(
cmap=None,
n=None,
smoothing=None,
randseed=None,
doshow=True,
)Demonstrate a color map using simulated elevation data, shown in both 2D and 3D. The argument can be either a colormap itself or a string describing a colormap.
Examples:
sc.colormapdemo('inferno') # Use a registered Matplotlib colormap
sc.colormapdemo('parula') # Use a registered Sciris colormap
sc.colormapdemo(sc.alpinecolormap(), n=200, smoothing=20, randseed=2942) # Use a colormap objectVersion: 2019aug22
gridcolors
sc_colors.gridcolors(
ncolors=10,
limits=None,
nsteps=20,
asarray=False,
ashex=False,
reverse=False,
hueshift=0,
basis='default',
demo=False,
)Create a qualitative “color map” by assigning points according to the maximum pairwise distance in the color cube. Basically, the algorithm generates n points that are maximally uniformly spaced in the [R, G, B] color cube.
By default, if there are <=9 colors, use Colorbrewer colors; if there are 10-19 colors, use Kelly’s colors; if there are >=20 colors, use uniformly spaced grid colors.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| ncolors (int) | the number of colors to create | required | |
| limits (float) | how close to the edges of the cube to make colors (to avoid white and black) | required | |
| nsteps (int) | the discretization of the color cube (e.g. 10 = 10 units per side = 1000 points total) | required | |
| ashex (bool) | whether to return colors in hexadecimal representation | required | |
| asarray (bool) | whether to return the colors as an array instead of as a list of tuples | required | |
| reverse (bool) | whether to reverse the list of colors | required | |
| hueshift (float) | whether to shift the hue (hueshift > 0 and <=1) or not (0) | required | |
| demo (bool) | whether or not to plot the color cube itself | required | |
| basis (str) | what basis to use – options are ‘colorbrewer’, ‘kelly’, ‘default’, or ‘none’ | required |
Example:
import numpy as np
import matplotlib.pyplot as plt
import sciris as sc
ncolors = 10
piedata = np.random.rand(ncolors)
colors = sc.gridcolors(ncolors)
plt.pie(piedata, colors=colors)
sc.gridcolors(ncolors, demo=True)
plt.show()- New in version 2018oct30.
- New in version 3.2.0: allow ncolors to be an iterable
hex2rgb
sc_colors.hex2rgb(string)A little helper function to convert e.g. ‘87bc26’ to a pleasing shade of green.
Example:
rgb = sc.hex2rgb('#87bc26') # Returns array([0.52941176, 0.7372549 , 0.14901961])hsv2rgb
sc_colors.hsv2rgb(colors=None)Shortcut to Matplotlib’s hsv_to_rgb method, accepts a color triplet or a list/array of color triplets.
Example:
rgb = sc.hsv2rgb([0.23, 0.80, 0.74]) # Returns array([0.51504, 0.74 , 0.148 ])manualcolorbar
sc_colors.manualcolorbar(
data=None,
vmin=0,
vmax=1,
vcenter=None,
colors=None,
values=None,
cmap=None,
norm=None,
label=None,
labelkwargs=None,
ticks=None,
ticklabels=None,
fig=None,
ax=None,
cax=None,
axkwargs=None,
**kwargs,
)Add a colorbar to a plot that does not support one by default.
There are three main use cases, from least to most manual:
- The most common use case is to supply the data used for plotting directly via `data`;
the function will the infer the lower and upper limits and construct the colorbar.
- Alternatively, the lower and upper limits can be provided manually via `vmin` and `vmax`.
- Finally, the colors themselves can be provided via `colors`, optionally mapped
to `values`, and potentially also supplied with custom `ticklabels`.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| data | arr |
if provided, compute the colorbar from these data | None |
| vmin | float | the minimum of the colormap (optional if data are provided) | 0 |
| vmax | float | the maximum of the colormap (optional if data are provided) | 1 |
| vcenter | float | the center of the colormap (optional) | None |
| colors | arr |
if provided, use these colors directly instead | None |
| values | arr |
if provided, the values corresponding to the specific colors | None |
| cmap | str / arr |
the colormap to use | None |
| norm | Norm |
the Matplotlib norm to use (if not provided, use the midpoint norm with vmin, vmax, etc.) | None |
| label | str | the label for the colorbar | None |
| labelkwargs | dict | passed to the colorbar label | None |
| ticks | list | the tick locations to use for the colorbar | None |
| ticklabels | list | the tick labels to use | None |
| ax | Axes |
the “parent” axes to associate the colorbar with | None |
| cax | Axes |
the axes to draw the colorbar into | None |
| axkwargs | dict | if creating a new colorbar axes, the arguments for creating it | None |
| kwargs | dict | passed to matplotlib.colorbar.ColorbarBase |
{} |
Examples:
# Create a default colorbar
sc.manualcolorbar()
# Add a colorbar to non-mappable data (e.g. a scatterplot)
n = 1000
x = np.random.randn(n)
y = np.random.randn(n)
c = x**2 + y**2
plt.scatter(x, y, c=c)
sc.manualcolorbar(c)
# Create a custom colorbar with a custom label
sc.manualcolorbar(
vmin=-20,
vmax=40,
vcenter=0,
cmap='orangeblue',
label='Cold/hot',
orientation='horizontal',
labelkwargs=dict(rotation=10, fontweight='bold'),
axkwargs=[0.1,0.5,0.8,0.1],
)
# Create a completely custom colorbar
n = 12
x = np.arange(n)
values = np.sqrt(np.arange(n))
colors = sc.gridcolors(n)
plt.scatter(x, values, c=colors)
plt.grid(True)
ticklabels = ['' for i in range(n)]
for i in [0, 2, 4, 10, 11]:
ticklabels[i] = f'Color {i} is nice'
cb = sc.manualcolorbar(
colors=colors,
values=values,
ticks=values,
ticklabels=ticklabels,
spacing='proportional'
)- New in version 3.1.0.
midpointnorm
sc_colors.midpointnorm(vcenter=0, vmin=None, vmax=None)Alias to Matplotlib’s TwoSlopeNorm. Used to place the center of the colormap somewhere other than the center of the data.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| vcenter | float | the center of the colormap (0 by default) | 0 |
| vmin | float | the minimum of the colormap | None |
| vmax | float | the maximum of the colormap | None |
Example:
data = np.random.rand(10,10) - 0.2
plt.pcolor(data, cmap='bi', norm=sc.midpointnorm())- New in version 1.2.0.
orangebluecolormap
sc_colors.orangebluecolormap(apply=False)Create an orange-blue colormap; most like RdYlBu but more pleasing. Created by Prashanth Selvaraj.
Demo and example:
cmap = sc.orangebluecolormap()
sc.colormapdemo(cmap=cmap)- New in version 1.0.0.
parulacolormap
sc_colors.parulacolormap(apply=False)Create a map similar to Viridis, but brighter. Set apply=True to use immediately.
Demo and example:
cmap = sc.parulacolormap()
sc.colormapdemo(cmap=cmap)Version: 2019aug22
rgb2hex
sc_colors.rgb2hex(arr)A little helper function to convert e.g. [0.53, 0.74, 0.15] to a pleasing shade of green.
Example:
hx = sc.rgb2hex([0.53, 0.74, 0.15]) # Returns '#87bc26'rgb2hsv
sc_colors.rgb2hsv(colors=None)Shortcut to Matplotlib’s rgb_to_hsv method, accepts a color triplet or a list/array of color triplets.
Example:
hsv = sc.rgb2hsv([0.53, 0.74, 0.15]) # Returns array([0.2259887, 0.7972973, 0.74 ])sanitizecolor
sc_colors.sanitizecolor(color, asarray=False, alpha=None, normalize=True)Alias to matplotlib.colors.to_rgb, but also handles numeric inputs.
Arg
color (str/list/etc): the input color to sanitize into an RGB tuple (or array) asarray (bool): whether to return an array instead of a tuple alpha (float): if not None, include the alpha channel with this value normalize (bool): whether to divide by 255 if any values are greater than 1
Examples:
green1 = sc.sanitizecolor('g')
green2 = sc.sanitizecolor('tab:green')
crimson1 = sc.sanitizecolor('crimson')
crimson2 = sc.sanitizecolor((220, 20, 60))
midgrey = sc.sanitizecolor(0.5)shifthue
sc_colors.shifthue(colors=None, hueshift=0.0)Shift the hue of the colors being fed in.
Example:
colors = sc.shifthue(colors=[(1,0,0),(0,1,0)], hueshift=0.5)turbocolormap
sc_colors.turbocolormap(apply=False)NOTE: as of Matplotlib 3.4.0, this colormap is included by default, and will soon be removed from Sciris.
Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0
Author: Anton Mikhailov
Borrowed directly from https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f, with thanks!
Create a map similar to Jet, but better. Set apply=True to use immediately.
Demo and example:
cmap = sc.turbocolormap()
sc.colormapdemo(cmap=cmap)Version: 2020mar20
vectocolor
sc_colors.vectocolor(
vector,
cmap=None,
asarray=True,
reverse=False,
minval=None,
maxval=None,
midpoint=None,
nancolor=None,
)This function converts a vector (i.e., 1D array) of N values into an Nx3 matrix of color values according to the current colormap. It automatically scales the vector to provide maximum dynamic range for the color map.
Note: see sc.arraycolors() for multidimensional input.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| vector | array | Input vector (or list, it’s converted to an array) | required |
| cmap | str | is the colormap (default: current) | None |
| asarray | bool | whether to return as an array (otherwise, a list of tuples) | True |
| reverse | bool | whether to reverse the list of colors | False |
| minval | float | the minimum value to use | None |
| maxval | float | the maximum value to use | None |
| midpoint | float | the midpoint value to use | None |
| nancolor | color |
if supplied, use this color for NaN entries | None |
Returns
| Name | Type | Description |
|---|---|---|
| colors | array | Nx4 array of RGB-alpha color values |
Example:
n = 1000
x = np.random.randn(n,1);
y = np.random.randn(n,1);
c = sc.vectocolor(y);
plt.scatter(x, y, c=c, s=50)- New in version 1.2.0: midpoint argument.
- New in version 2.1.0: nancolor argument and remove nans by default
- New in version 3.0.0: correct “midpoint” argument