palettes.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. import colorsys
  2. from itertools import cycle
  3. import numpy as np
  4. import matplotlib as mpl
  5. from .external import husl
  6. from .utils import desaturate, set_hls_values, get_color_cycle
  7. from .colors import xkcd_rgb, crayons
  8. __all__ = ["color_palette", "hls_palette", "husl_palette", "mpl_palette",
  9. "dark_palette", "light_palette", "diverging_palette",
  10. "blend_palette", "xkcd_palette", "crayon_palette",
  11. "cubehelix_palette", "set_color_codes"]
  12. SEABORN_PALETTES = dict(
  13. deep=["#4C72B0", "#DD8452", "#55A868", "#C44E52", "#8172B3",
  14. "#937860", "#DA8BC3", "#8C8C8C", "#CCB974", "#64B5CD"],
  15. deep6=["#4C72B0", "#55A868", "#C44E52",
  16. "#8172B3", "#CCB974", "#64B5CD"],
  17. muted=["#4878D0", "#EE854A", "#6ACC64", "#D65F5F", "#956CB4",
  18. "#8C613C", "#DC7EC0", "#797979", "#D5BB67", "#82C6E2"],
  19. muted6=["#4878D0", "#6ACC64", "#D65F5F",
  20. "#956CB4", "#D5BB67", "#82C6E2"],
  21. pastel=["#A1C9F4", "#FFB482", "#8DE5A1", "#FF9F9B", "#D0BBFF",
  22. "#DEBB9B", "#FAB0E4", "#CFCFCF", "#FFFEA3", "#B9F2F0"],
  23. pastel6=["#A1C9F4", "#8DE5A1", "#FF9F9B",
  24. "#D0BBFF", "#FFFEA3", "#B9F2F0"],
  25. bright=["#023EFF", "#FF7C00", "#1AC938", "#E8000B", "#8B2BE2",
  26. "#9F4800", "#F14CC1", "#A3A3A3", "#FFC400", "#00D7FF"],
  27. bright6=["#023EFF", "#1AC938", "#E8000B",
  28. "#8B2BE2", "#FFC400", "#00D7FF"],
  29. dark=["#001C7F", "#B1400D", "#12711C", "#8C0800", "#591E71",
  30. "#592F0D", "#A23582", "#3C3C3C", "#B8850A", "#006374"],
  31. dark6=["#001C7F", "#12711C", "#8C0800",
  32. "#591E71", "#B8850A", "#006374"],
  33. colorblind=["#0173B2", "#DE8F05", "#029E73", "#D55E00", "#CC78BC",
  34. "#CA9161", "#FBAFE4", "#949494", "#ECE133", "#56B4E9"],
  35. colorblind6=["#0173B2", "#029E73", "#D55E00",
  36. "#CC78BC", "#ECE133", "#56B4E9"]
  37. )
  38. MPL_QUAL_PALS = {
  39. "tab10": 10, "tab20": 20, "tab20b": 20, "tab20c": 20,
  40. "Set1": 9, "Set2": 8, "Set3": 12,
  41. "Accent": 8, "Paired": 12,
  42. "Pastel1": 9, "Pastel2": 8, "Dark2": 8,
  43. }
  44. QUAL_PALETTE_SIZES = MPL_QUAL_PALS.copy()
  45. QUAL_PALETTE_SIZES.update({k: len(v) for k, v in SEABORN_PALETTES.items()})
  46. QUAL_PALETTES = list(QUAL_PALETTE_SIZES.keys())
  47. class _ColorPalette(list):
  48. """Set the color palette in a with statement, otherwise be a list."""
  49. def __enter__(self):
  50. """Open the context."""
  51. from .rcmod import set_palette
  52. self._orig_palette = color_palette()
  53. set_palette(self)
  54. return self
  55. def __exit__(self, *args):
  56. """Close the context."""
  57. from .rcmod import set_palette
  58. set_palette(self._orig_palette)
  59. def as_hex(self):
  60. """Return a color palette with hex codes instead of RGB values."""
  61. hex = [mpl.colors.rgb2hex(rgb) for rgb in self]
  62. return _ColorPalette(hex)
  63. def color_palette(palette=None, n_colors=None, desat=None):
  64. """Return a list of colors defining a color palette.
  65. Available seaborn palette names:
  66. deep, muted, bright, pastel, dark, colorblind
  67. Other options:
  68. name of matplotlib cmap, 'ch:<cubehelix arguments>', 'hls', 'husl',
  69. or a list of colors in any format matplotlib accepts
  70. Calling this function with ``palette=None`` will return the current
  71. matplotlib color cycle.
  72. Matplotlib palettes can be specified as reversed palettes by appending
  73. "_r" to the name or as "dark" palettes by appending "_d" to the name.
  74. (These options are mutually exclusive, but the resulting list of colors
  75. can also be reversed).
  76. This function can also be used in a ``with`` statement to temporarily
  77. set the color cycle for a plot or set of plots.
  78. See the :ref:`tutorial <palette_tutorial>` for more information.
  79. Parameters
  80. ----------
  81. palette: None, string, or sequence, optional
  82. Name of palette or None to return current palette. If a sequence, input
  83. colors are used but possibly cycled and desaturated.
  84. n_colors : int, optional
  85. Number of colors in the palette. If ``None``, the default will depend
  86. on how ``palette`` is specified. Named palettes default to 6 colors,
  87. but grabbing the current palette or passing in a list of colors will
  88. not change the number of colors unless this is specified. Asking for
  89. more colors than exist in the palette will cause it to cycle.
  90. desat : float, optional
  91. Proportion to desaturate each color by.
  92. Returns
  93. -------
  94. palette : list of RGB tuples.
  95. Color palette. Behaves like a list, but can be used as a context
  96. manager and possesses an ``as_hex`` method to convert to hex color
  97. codes.
  98. See Also
  99. --------
  100. set_palette : Set the default color cycle for all plots.
  101. set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
  102. colors from one of the seaborn palettes.
  103. Examples
  104. --------
  105. Calling with no arguments returns all colors from the current default
  106. color cycle:
  107. .. plot::
  108. :context: close-figs
  109. >>> import seaborn as sns; sns.set()
  110. >>> sns.palplot(sns.color_palette())
  111. Show one of the other "seaborn palettes", which have the same basic order
  112. of hues as the default matplotlib color cycle but more attractive colors.
  113. Calling with the name of a palette will return 6 colors by default:
  114. .. plot::
  115. :context: close-figs
  116. >>> sns.palplot(sns.color_palette("muted"))
  117. Use discrete values from one of the built-in matplotlib colormaps:
  118. .. plot::
  119. :context: close-figs
  120. >>> sns.palplot(sns.color_palette("RdBu", n_colors=7))
  121. Make a customized cubehelix color palette:
  122. .. plot::
  123. :context: close-figs
  124. >>> sns.palplot(sns.color_palette("ch:2.5,-.2,dark=.3"))
  125. Use a categorical matplotlib palette and add some desaturation:
  126. .. plot::
  127. :context: close-figs
  128. >>> sns.palplot(sns.color_palette("Set1", n_colors=8, desat=.5))
  129. Make a "dark" matplotlib sequential palette variant. (This can be good
  130. when coloring multiple lines or points that correspond to an ordered
  131. variable, where you don't want the lightest lines to be invisible):
  132. .. plot::
  133. :context: close-figs
  134. >>> sns.palplot(sns.color_palette("Blues_d"))
  135. Use as a context manager:
  136. .. plot::
  137. :context: close-figs
  138. >>> import numpy as np, matplotlib.pyplot as plt
  139. >>> with sns.color_palette("husl", 8):
  140. ... _ = plt.plot(np.c_[np.zeros(8), np.arange(8)].T)
  141. """
  142. if palette is None:
  143. palette = get_color_cycle()
  144. if n_colors is None:
  145. n_colors = len(palette)
  146. elif not isinstance(palette, str):
  147. palette = palette
  148. if n_colors is None:
  149. n_colors = len(palette)
  150. else:
  151. if n_colors is None:
  152. # Use all colors in a qualitative palette or 6 of another kind
  153. n_colors = QUAL_PALETTE_SIZES.get(palette, 6)
  154. if palette in SEABORN_PALETTES:
  155. # Named "seaborn variant" of old matplotlib default palette
  156. palette = SEABORN_PALETTES[palette]
  157. elif palette == "hls":
  158. # Evenly spaced colors in cylindrical RGB space
  159. palette = hls_palette(n_colors)
  160. elif palette == "husl":
  161. # Evenly spaced colors in cylindrical Lab space
  162. palette = husl_palette(n_colors)
  163. elif palette.lower() == "jet":
  164. # Paternalism
  165. raise ValueError("No.")
  166. elif palette.startswith("ch:"):
  167. # Cubehelix palette with params specified in string
  168. args, kwargs = _parse_cubehelix_args(palette)
  169. palette = cubehelix_palette(n_colors, *args, **kwargs)
  170. else:
  171. try:
  172. # Perhaps a named matplotlib colormap?
  173. palette = mpl_palette(palette, n_colors)
  174. except ValueError:
  175. raise ValueError("%s is not a valid palette name" % palette)
  176. if desat is not None:
  177. palette = [desaturate(c, desat) for c in palette]
  178. # Always return as many colors as we asked for
  179. pal_cycle = cycle(palette)
  180. palette = [next(pal_cycle) for _ in range(n_colors)]
  181. # Always return in r, g, b tuple format
  182. try:
  183. palette = map(mpl.colors.colorConverter.to_rgb, palette)
  184. palette = _ColorPalette(palette)
  185. except ValueError:
  186. raise ValueError("Could not generate a palette for %s" % str(palette))
  187. return palette
  188. def hls_palette(n_colors=6, h=.01, l=.6, s=.65): # noqa
  189. """Get a set of evenly spaced colors in HLS hue space.
  190. h, l, and s should be between 0 and 1
  191. Parameters
  192. ----------
  193. n_colors : int
  194. number of colors in the palette
  195. h : float
  196. first hue
  197. l : float
  198. lightness
  199. s : float
  200. saturation
  201. Returns
  202. -------
  203. palette : seaborn color palette
  204. List-like object of colors as RGB tuples.
  205. See Also
  206. --------
  207. husl_palette : Make a palette using evently spaced circular hues in the
  208. HUSL system.
  209. Examples
  210. --------
  211. Create a palette of 10 colors with the default parameters:
  212. .. plot::
  213. :context: close-figs
  214. >>> import seaborn as sns; sns.set()
  215. >>> sns.palplot(sns.hls_palette(10))
  216. Create a palette of 10 colors that begins at a different hue value:
  217. .. plot::
  218. :context: close-figs
  219. >>> sns.palplot(sns.hls_palette(10, h=.5))
  220. Create a palette of 10 colors that are darker than the default:
  221. .. plot::
  222. :context: close-figs
  223. >>> sns.palplot(sns.hls_palette(10, l=.4))
  224. Create a palette of 10 colors that are less saturated than the default:
  225. .. plot::
  226. :context: close-figs
  227. >>> sns.palplot(sns.hls_palette(10, s=.4))
  228. """
  229. hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]
  230. hues += h
  231. hues %= 1
  232. hues -= hues.astype(int)
  233. palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]
  234. return _ColorPalette(palette)
  235. def husl_palette(n_colors=6, h=.01, s=.9, l=.65): # noqa
  236. """Get a set of evenly spaced colors in HUSL hue space.
  237. h, s, and l should be between 0 and 1
  238. Parameters
  239. ----------
  240. n_colors : int
  241. number of colors in the palette
  242. h : float
  243. first hue
  244. s : float
  245. saturation
  246. l : float
  247. lightness
  248. Returns
  249. -------
  250. palette : seaborn color palette
  251. List-like object of colors as RGB tuples.
  252. See Also
  253. --------
  254. hls_palette : Make a palette using evently spaced circular hues in the
  255. HSL system.
  256. Examples
  257. --------
  258. Create a palette of 10 colors with the default parameters:
  259. .. plot::
  260. :context: close-figs
  261. >>> import seaborn as sns; sns.set()
  262. >>> sns.palplot(sns.husl_palette(10))
  263. Create a palette of 10 colors that begins at a different hue value:
  264. .. plot::
  265. :context: close-figs
  266. >>> sns.palplot(sns.husl_palette(10, h=.5))
  267. Create a palette of 10 colors that are darker than the default:
  268. .. plot::
  269. :context: close-figs
  270. >>> sns.palplot(sns.husl_palette(10, l=.4))
  271. Create a palette of 10 colors that are less saturated than the default:
  272. .. plot::
  273. :context: close-figs
  274. >>> sns.palplot(sns.husl_palette(10, s=.4))
  275. """
  276. hues = np.linspace(0, 1, int(n_colors) + 1)[:-1]
  277. hues += h
  278. hues %= 1
  279. hues *= 359
  280. s *= 99
  281. l *= 99 # noqa
  282. palette = [_color_to_rgb((h_i, s, l), input='husl') for h_i in hues]
  283. return _ColorPalette(palette)
  284. def mpl_palette(name, n_colors=6):
  285. """Return discrete colors from a matplotlib palette.
  286. Note that this handles the qualitative colorbrewer palettes
  287. properly, although if you ask for more colors than a particular
  288. qualitative palette can provide you will get fewer than you are
  289. expecting. In contrast, asking for qualitative color brewer palettes
  290. using :func:`color_palette` will return the expected number of colors,
  291. but they will cycle.
  292. If you are using the IPython notebook, you can also use the function
  293. :func:`choose_colorbrewer_palette` to interactively select palettes.
  294. Parameters
  295. ----------
  296. name : string
  297. Name of the palette. This should be a named matplotlib colormap.
  298. n_colors : int
  299. Number of discrete colors in the palette.
  300. Returns
  301. -------
  302. palette or cmap : seaborn color palette or matplotlib colormap
  303. List-like object of colors as RGB tuples, or colormap object that
  304. can map continuous values to colors, depending on the value of the
  305. ``as_cmap`` parameter.
  306. Examples
  307. --------
  308. Create a qualitative colorbrewer palette with 8 colors:
  309. .. plot::
  310. :context: close-figs
  311. >>> import seaborn as sns; sns.set()
  312. >>> sns.palplot(sns.mpl_palette("Set2", 8))
  313. Create a sequential colorbrewer palette:
  314. .. plot::
  315. :context: close-figs
  316. >>> sns.palplot(sns.mpl_palette("Blues"))
  317. Create a diverging palette:
  318. .. plot::
  319. :context: close-figs
  320. >>> sns.palplot(sns.mpl_palette("seismic", 8))
  321. Create a "dark" sequential palette:
  322. .. plot::
  323. :context: close-figs
  324. >>> sns.palplot(sns.mpl_palette("GnBu_d"))
  325. """
  326. if name.endswith("_d"):
  327. pal = ["#333333"]
  328. pal.extend(color_palette(name.replace("_d", "_r"), 2))
  329. cmap = blend_palette(pal, n_colors, as_cmap=True)
  330. else:
  331. cmap = mpl.cm.get_cmap(name)
  332. if cmap is None:
  333. raise ValueError("{} is not a valid colormap".format(name))
  334. if name in MPL_QUAL_PALS:
  335. bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors]
  336. else:
  337. bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1]
  338. palette = list(map(tuple, cmap(bins)[:, :3]))
  339. return _ColorPalette(palette)
  340. def _color_to_rgb(color, input):
  341. """Add some more flexibility to color choices."""
  342. if input == "hls":
  343. color = colorsys.hls_to_rgb(*color)
  344. elif input == "husl":
  345. color = husl.husl_to_rgb(*color)
  346. color = tuple(np.clip(color, 0, 1))
  347. elif input == "xkcd":
  348. color = xkcd_rgb[color]
  349. return color
  350. def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
  351. """Make a sequential palette that blends from dark to ``color``.
  352. This kind of palette is good for data that range between relatively
  353. uninteresting low values and interesting high values.
  354. The ``color`` parameter can be specified in a number of ways, including
  355. all options for defining a color in matplotlib and several additional
  356. color spaces that are handled by seaborn. You can also use the database
  357. of named colors from the XKCD color survey.
  358. If you are using the IPython notebook, you can also choose this palette
  359. interactively with the :func:`choose_dark_palette` function.
  360. Parameters
  361. ----------
  362. color : base color for high values
  363. hex, rgb-tuple, or html color name
  364. n_colors : int, optional
  365. number of colors in the palette
  366. reverse : bool, optional
  367. if True, reverse the direction of the blend
  368. as_cmap : bool, optional
  369. if True, return as a matplotlib colormap instead of list
  370. input : {'rgb', 'hls', 'husl', xkcd'}
  371. Color space to interpret the input color. The first three options
  372. apply to tuple inputs and the latter applies to string inputs.
  373. Returns
  374. -------
  375. palette or cmap : seaborn color palette or matplotlib colormap
  376. List-like object of colors as RGB tuples, or colormap object that
  377. can map continuous values to colors, depending on the value of the
  378. ``as_cmap`` parameter.
  379. See Also
  380. --------
  381. light_palette : Create a sequential palette with bright low values.
  382. diverging_palette : Create a diverging palette with two colors.
  383. Examples
  384. --------
  385. Generate a palette from an HTML color:
  386. .. plot::
  387. :context: close-figs
  388. >>> import seaborn as sns; sns.set()
  389. >>> sns.palplot(sns.dark_palette("purple"))
  390. Generate a palette that decreases in lightness:
  391. .. plot::
  392. :context: close-figs
  393. >>> sns.palplot(sns.dark_palette("seagreen", reverse=True))
  394. Generate a palette from an HUSL-space seed:
  395. .. plot::
  396. :context: close-figs
  397. >>> sns.palplot(sns.dark_palette((260, 75, 60), input="husl"))
  398. Generate a colormap object:
  399. .. plot::
  400. :context: close-figs
  401. >>> from numpy import arange
  402. >>> x = arange(25).reshape(5, 5)
  403. >>> cmap = sns.dark_palette("#2ecc71", as_cmap=True)
  404. >>> ax = sns.heatmap(x, cmap=cmap)
  405. """
  406. color = _color_to_rgb(color, input)
  407. gray = "#222222"
  408. colors = [color, gray] if reverse else [gray, color]
  409. return blend_palette(colors, n_colors, as_cmap)
  410. def light_palette(color, n_colors=6, reverse=False, as_cmap=False,
  411. input="rgb"):
  412. """Make a sequential palette that blends from light to ``color``.
  413. This kind of palette is good for data that range between relatively
  414. uninteresting low values and interesting high values.
  415. The ``color`` parameter can be specified in a number of ways, including
  416. all options for defining a color in matplotlib and several additional
  417. color spaces that are handled by seaborn. You can also use the database
  418. of named colors from the XKCD color survey.
  419. If you are using the IPython notebook, you can also choose this palette
  420. interactively with the :func:`choose_light_palette` function.
  421. Parameters
  422. ----------
  423. color : base color for high values
  424. hex code, html color name, or tuple in ``input`` space.
  425. n_colors : int, optional
  426. number of colors in the palette
  427. reverse : bool, optional
  428. if True, reverse the direction of the blend
  429. as_cmap : bool, optional
  430. if True, return as a matplotlib colormap instead of list
  431. input : {'rgb', 'hls', 'husl', xkcd'}
  432. Color space to interpret the input color. The first three options
  433. apply to tuple inputs and the latter applies to string inputs.
  434. Returns
  435. -------
  436. palette or cmap : seaborn color palette or matplotlib colormap
  437. List-like object of colors as RGB tuples, or colormap object that
  438. can map continuous values to colors, depending on the value of the
  439. ``as_cmap`` parameter.
  440. See Also
  441. --------
  442. dark_palette : Create a sequential palette with dark low values.
  443. diverging_palette : Create a diverging palette with two colors.
  444. Examples
  445. --------
  446. Generate a palette from an HTML color:
  447. .. plot::
  448. :context: close-figs
  449. >>> import seaborn as sns; sns.set()
  450. >>> sns.palplot(sns.light_palette("purple"))
  451. Generate a palette that increases in lightness:
  452. .. plot::
  453. :context: close-figs
  454. >>> sns.palplot(sns.light_palette("seagreen", reverse=True))
  455. Generate a palette from an HUSL-space seed:
  456. .. plot::
  457. :context: close-figs
  458. >>> sns.palplot(sns.light_palette((260, 75, 60), input="husl"))
  459. Generate a colormap object:
  460. .. plot::
  461. :context: close-figs
  462. >>> from numpy import arange
  463. >>> x = arange(25).reshape(5, 5)
  464. >>> cmap = sns.light_palette("#2ecc71", as_cmap=True)
  465. >>> ax = sns.heatmap(x, cmap=cmap)
  466. """
  467. color = _color_to_rgb(color, input)
  468. light = set_hls_values(color, l=.95) # noqa
  469. colors = [color, light] if reverse else [light, color]
  470. return blend_palette(colors, n_colors, as_cmap)
  471. def _flat_palette(color, n_colors=6, reverse=False, as_cmap=False,
  472. input="rgb"):
  473. """Make a sequential palette that blends from gray to ``color``.
  474. Parameters
  475. ----------
  476. color : matplotlib color
  477. hex, rgb-tuple, or html color name
  478. n_colors : int, optional
  479. number of colors in the palette
  480. reverse : bool, optional
  481. if True, reverse the direction of the blend
  482. as_cmap : bool, optional
  483. if True, return as a matplotlib colormap instead of list
  484. Returns
  485. -------
  486. palette : list or colormap
  487. dark_palette : Create a sequential palette with dark low values.
  488. """
  489. color = _color_to_rgb(color, input)
  490. flat = desaturate(color, 0)
  491. colors = [color, flat] if reverse else [flat, color]
  492. return blend_palette(colors, n_colors, as_cmap)
  493. def diverging_palette(h_neg, h_pos, s=75, l=50, sep=10, n=6, # noqa
  494. center="light", as_cmap=False):
  495. """Make a diverging palette between two HUSL colors.
  496. If you are using the IPython notebook, you can also choose this palette
  497. interactively with the :func:`choose_diverging_palette` function.
  498. Parameters
  499. ----------
  500. h_neg, h_pos : float in [0, 359]
  501. Anchor hues for negative and positive extents of the map.
  502. s : float in [0, 100], optional
  503. Anchor saturation for both extents of the map.
  504. l : float in [0, 100], optional
  505. Anchor lightness for both extents of the map.
  506. sep : int, optional
  507. Size of the intermediate region.
  508. n : int, optional
  509. Number of colors in the palette (if not returning a cmap)
  510. center : {"light", "dark"}, optional
  511. Whether the center of the palette is light or dark
  512. as_cmap : bool, optional
  513. If true, return a matplotlib colormap object rather than a
  514. list of colors.
  515. Returns
  516. -------
  517. palette or cmap : seaborn color palette or matplotlib colormap
  518. List-like object of colors as RGB tuples, or colormap object that
  519. can map continuous values to colors, depending on the value of the
  520. ``as_cmap`` parameter.
  521. See Also
  522. --------
  523. dark_palette : Create a sequential palette with dark values.
  524. light_palette : Create a sequential palette with light values.
  525. Examples
  526. --------
  527. Generate a blue-white-red palette:
  528. .. plot::
  529. :context: close-figs
  530. >>> import seaborn as sns; sns.set()
  531. >>> sns.palplot(sns.diverging_palette(240, 10, n=9))
  532. Generate a brighter green-white-purple palette:
  533. .. plot::
  534. :context: close-figs
  535. >>> sns.palplot(sns.diverging_palette(150, 275, s=80, l=55, n=9))
  536. Generate a blue-black-red palette:
  537. .. plot::
  538. :context: close-figs
  539. >>> sns.palplot(sns.diverging_palette(250, 15, s=75, l=40,
  540. ... n=9, center="dark"))
  541. Generate a colormap object:
  542. .. plot::
  543. :context: close-figs
  544. >>> from numpy import arange
  545. >>> x = arange(25).reshape(5, 5)
  546. >>> cmap = sns.diverging_palette(220, 20, sep=20, as_cmap=True)
  547. >>> ax = sns.heatmap(x, cmap=cmap)
  548. """
  549. palfunc = dark_palette if center == "dark" else light_palette
  550. n_half = int(128 - (sep // 2))
  551. neg = palfunc((h_neg, s, l), n_half, reverse=True, input="husl")
  552. pos = palfunc((h_pos, s, l), n_half, input="husl")
  553. midpoint = dict(light=[(.95, .95, .95)], dark=[(.133, .133, .133)])[center]
  554. mid = midpoint * sep
  555. pal = blend_palette(np.concatenate([neg, mid, pos]), n, as_cmap=as_cmap)
  556. return pal
  557. def blend_palette(colors, n_colors=6, as_cmap=False, input="rgb"):
  558. """Make a palette that blends between a list of colors.
  559. Parameters
  560. ----------
  561. colors : sequence of colors in various formats interpreted by ``input``
  562. hex code, html color name, or tuple in ``input`` space.
  563. n_colors : int, optional
  564. Number of colors in the palette.
  565. as_cmap : bool, optional
  566. If True, return as a matplotlib colormap instead of list.
  567. Returns
  568. -------
  569. palette or cmap : seaborn color palette or matplotlib colormap
  570. List-like object of colors as RGB tuples, or colormap object that
  571. can map continuous values to colors, depending on the value of the
  572. ``as_cmap`` parameter.
  573. """
  574. colors = [_color_to_rgb(color, input) for color in colors]
  575. name = "blend"
  576. pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)
  577. if not as_cmap:
  578. rgb_array = pal(np.linspace(0, 1, int(n_colors)))[:, :3] # no alpha
  579. pal = _ColorPalette(map(tuple, rgb_array))
  580. return pal
  581. def xkcd_palette(colors):
  582. """Make a palette with color names from the xkcd color survey.
  583. See xkcd for the full list of colors: https://xkcd.com/color/rgb/
  584. This is just a simple wrapper around the ``seaborn.xkcd_rgb`` dictionary.
  585. Parameters
  586. ----------
  587. colors : list of strings
  588. List of keys in the ``seaborn.xkcd_rgb`` dictionary.
  589. Returns
  590. -------
  591. palette : seaborn color palette
  592. Returns the list of colors as RGB tuples in an object that behaves like
  593. other seaborn color palettes.
  594. See Also
  595. --------
  596. crayon_palette : Make a palette with Crayola crayon colors.
  597. """
  598. palette = [xkcd_rgb[name] for name in colors]
  599. return color_palette(palette, len(palette))
  600. def crayon_palette(colors):
  601. """Make a palette with color names from Crayola crayons.
  602. Colors are taken from here:
  603. https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors
  604. This is just a simple wrapper around the ``seaborn.crayons`` dictionary.
  605. Parameters
  606. ----------
  607. colors : list of strings
  608. List of keys in the ``seaborn.crayons`` dictionary.
  609. Returns
  610. -------
  611. palette : seaborn color palette
  612. Returns the list of colors as rgb tuples in an object that behaves like
  613. other seaborn color palettes.
  614. See Also
  615. --------
  616. xkcd_palette : Make a palette with named colors from the XKCD color survey.
  617. """
  618. palette = [crayons[name] for name in colors]
  619. return color_palette(palette, len(palette))
  620. def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,
  621. light=.85, dark=.15, reverse=False, as_cmap=False):
  622. """Make a sequential palette from the cubehelix system.
  623. This produces a colormap with linearly-decreasing (or increasing)
  624. brightness. That means that information will be preserved if printed to
  625. black and white or viewed by someone who is colorblind. "cubehelix" is
  626. also available as a matplotlib-based palette, but this function gives the
  627. user more control over the look of the palette and has a different set of
  628. defaults.
  629. In addition to using this function, it is also possible to generate a
  630. cubehelix palette generally in seaborn using a string-shorthand; see the
  631. example below.
  632. Parameters
  633. ----------
  634. n_colors : int
  635. Number of colors in the palette.
  636. start : float, 0 <= start <= 3
  637. The hue at the start of the helix.
  638. rot : float
  639. Rotations around the hue wheel over the range of the palette.
  640. gamma : float 0 <= gamma
  641. Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
  642. colors.
  643. hue : float, 0 <= hue <= 1
  644. Saturation of the colors.
  645. dark : float 0 <= dark <= 1
  646. Intensity of the darkest color in the palette.
  647. light : float 0 <= light <= 1
  648. Intensity of the lightest color in the palette.
  649. reverse : bool
  650. If True, the palette will go from dark to light.
  651. as_cmap : bool
  652. If True, return a matplotlib colormap instead of a list of colors.
  653. Returns
  654. -------
  655. palette or cmap : seaborn color palette or matplotlib colormap
  656. List-like object of colors as RGB tuples, or colormap object that
  657. can map continuous values to colors, depending on the value of the
  658. ``as_cmap`` parameter.
  659. See Also
  660. --------
  661. choose_cubehelix_palette : Launch an interactive widget to select cubehelix
  662. palette parameters.
  663. dark_palette : Create a sequential palette with dark low values.
  664. light_palette : Create a sequential palette with bright low values.
  665. References
  666. ----------
  667. Green, D. A. (2011). "A colour scheme for the display of astronomical
  668. intensity images". Bulletin of the Astromical Society of India, Vol. 39,
  669. p. 289-295.
  670. Examples
  671. --------
  672. Generate the default palette:
  673. .. plot::
  674. :context: close-figs
  675. >>> import seaborn as sns; sns.set()
  676. >>> sns.palplot(sns.cubehelix_palette())
  677. Rotate backwards from the same starting location:
  678. .. plot::
  679. :context: close-figs
  680. >>> sns.palplot(sns.cubehelix_palette(rot=-.4))
  681. Use a different starting point and shorter rotation:
  682. .. plot::
  683. :context: close-figs
  684. >>> sns.palplot(sns.cubehelix_palette(start=2.8, rot=.1))
  685. Reverse the direction of the lightness ramp:
  686. .. plot::
  687. :context: close-figs
  688. >>> sns.palplot(sns.cubehelix_palette(reverse=True))
  689. Generate a colormap object:
  690. .. plot::
  691. :context: close-figs
  692. >>> from numpy import arange
  693. >>> x = arange(25).reshape(5, 5)
  694. >>> cmap = sns.cubehelix_palette(as_cmap=True)
  695. >>> ax = sns.heatmap(x, cmap=cmap)
  696. Use the full lightness range:
  697. .. plot::
  698. :context: close-figs
  699. >>> cmap = sns.cubehelix_palette(dark=0, light=1, as_cmap=True)
  700. >>> ax = sns.heatmap(x, cmap=cmap)
  701. Use through the :func:`color_palette` interface:
  702. .. plot::
  703. :context: close-figs
  704. >>> sns.palplot(sns.color_palette("ch:2,r=.2,l=.6"))
  705. """
  706. def get_color_function(p0, p1):
  707. # Copied from matplotlib because it lives in private module
  708. def color(x):
  709. # Apply gamma factor to emphasise low or high intensity values
  710. xg = x ** gamma
  711. # Calculate amplitude and angle of deviation from the black
  712. # to white diagonal in the plane of constant
  713. # perceived intensity.
  714. a = hue * xg * (1 - xg) / 2
  715. phi = 2 * np.pi * (start / 3 + rot * x)
  716. return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))
  717. return color
  718. cdict = {
  719. "red": get_color_function(-0.14861, 1.78277),
  720. "green": get_color_function(-0.29227, -0.90649),
  721. "blue": get_color_function(1.97294, 0.0),
  722. }
  723. cmap = mpl.colors.LinearSegmentedColormap("cubehelix", cdict)
  724. x = np.linspace(light, dark, int(n_colors))
  725. pal = cmap(x)[:, :3].tolist()
  726. if reverse:
  727. pal = pal[::-1]
  728. if as_cmap:
  729. x_256 = np.linspace(light, dark, 256)
  730. if reverse:
  731. x_256 = x_256[::-1]
  732. pal_256 = cmap(x_256)
  733. cmap = mpl.colors.ListedColormap(pal_256, "seaborn_cubehelix")
  734. return cmap
  735. else:
  736. return _ColorPalette(pal)
  737. def _parse_cubehelix_args(argstr):
  738. """Turn stringified cubehelix params into args/kwargs."""
  739. if argstr.startswith("ch:"):
  740. argstr = argstr[3:]
  741. if argstr.endswith("_r"):
  742. reverse = True
  743. argstr = argstr[:-2]
  744. else:
  745. reverse = False
  746. if not argstr:
  747. return [], {"reverse": reverse}
  748. all_args = argstr.split(",")
  749. args = [float(a.strip(" ")) for a in all_args if "=" not in a]
  750. kwargs = [a.split("=") for a in all_args if "=" in a]
  751. kwargs = {k.strip(" "): float(v.strip(" ")) for k, v in kwargs}
  752. kwarg_map = dict(
  753. s="start", r="rot", g="gamma",
  754. h="hue", l="light", d="dark", # noqa: E741
  755. )
  756. kwargs = {kwarg_map.get(k, k): v for k, v in kwargs.items()}
  757. if reverse:
  758. kwargs["reverse"] = True
  759. return args, kwargs
  760. def set_color_codes(palette="deep"):
  761. """Change how matplotlib color shorthands are interpreted.
  762. Calling this will change how shorthand codes like "b" or "g"
  763. are interpreted by matplotlib in subsequent plots.
  764. Parameters
  765. ----------
  766. palette : {deep, muted, pastel, dark, bright, colorblind}
  767. Named seaborn palette to use as the source of colors.
  768. See Also
  769. --------
  770. set : Color codes can be set through the high-level seaborn style
  771. manager.
  772. set_palette : Color codes can also be set through the function that
  773. sets the matplotlib color cycle.
  774. Examples
  775. --------
  776. Map matplotlib color codes to the default seaborn palette.
  777. .. plot::
  778. :context: close-figs
  779. >>> import matplotlib.pyplot as plt
  780. >>> import seaborn as sns; sns.set()
  781. >>> sns.set_color_codes()
  782. >>> _ = plt.plot([0, 1], color="r")
  783. Use a different seaborn palette.
  784. .. plot::
  785. :context: close-figs
  786. >>> sns.set_color_codes("dark")
  787. >>> _ = plt.plot([0, 1], color="g")
  788. >>> _ = plt.plot([0, 2], color="m")
  789. """
  790. if palette == "reset":
  791. colors = [(0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, 0., .75),
  792. (.75, .75, 0.), (0., .75, .75), (0., 0., 0.)]
  793. elif not isinstance(palette, str):
  794. err = "set_color_codes requires a named seaborn palette"
  795. raise TypeError(err)
  796. elif palette in SEABORN_PALETTES:
  797. if not palette.endswith("6"):
  798. palette = palette + "6"
  799. colors = SEABORN_PALETTES[palette] + [(.1, .1, .1)]
  800. else:
  801. err = "Cannot set colors with palette '{}'".format(palette)
  802. raise ValueError(err)
  803. for code, color in zip("bgrmyck", colors):
  804. rgb = mpl.colors.colorConverter.to_rgb(color)
  805. mpl.colors.colorConverter.colors[code] = rgb
  806. mpl.colors.colorConverter.cache[code] = rgb