From cb9c28c5da8f1f16cb7d02ea4d52330afdf97f2b Mon Sep 17 00:00:00 2001 From: "Kristen M. Thyng" Date: Sat, 12 Jul 2014 17:48:05 -0500 Subject: [PATCH 1/6] working on guide for choosing colormaps. Have overview section and start on a few others. --- doc/users/colormaps.rst | 330 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 330 insertions(+) create mode 100644 doc/users/colormaps.rst diff --git a/doc/users/colormaps.rst b/doc/users/colormaps.rst new file mode 100644 index 000000000000..2621187a8c89 --- /dev/null +++ b/doc/users/colormaps.rst @@ -0,0 +1,330 @@ +.. _colormaps: + +****************** +Choosing Colormaps +****************** + + +Overview +======== + +The idea behind choosing a good colormap is to find a good representation in 3D colorspace for your data set. The best colormap for any given data set depends on many things including: + +- Whether representing form or metric data (link to C. Ware paper and explain more) +- Your knowledge of the data set (*i.e.*, is there a critical value from which the other values deviate?) +- If there is an intuitive color scheme for the parameter you are plotting +- If there is a standard in the field the audience may be expecting + +For many applications, a perceptual colormap is the best choice |---| one in which equal steps in data are perceived as equal steps in the color space. Researchers have found that the human brain perceives changes in the lightness parameter as changes in the data much better than, for example, changes in hue. Therefore, colormaps which have monotonically increasing lightness through the colormap will be better interpreted by the viewer. + +Color can be represented in 3D space in various ways. One way to represent color is using CIELAB (CITE). In CIELAB, color space is represented by lightness, :math:`L^*`; red-green, :math:`a`; and yellow-blue, :math:`b`. The lightness parameter :math:`L^*` can then be used to learn more about how the matplotlib colormaps will be perceived by viewers. + + +Sequential and diverging colormaps +================================== + +STUFF + + +Lightness of matplotlib colormaps +================================= + +.. plot:: users/plotting/colormaps/lightness.py + +For the Sequential plots, the lightness value increases monotonically through the colormaps. This is good. Some of the :math:`L^*` values in the colormaps span from 0 to 100 (binary and the other grayscale), and others start around :math:`L^*=20`. + +Some of the :math:`L^*` values from the Sequential2 plots are monotonically increasing, but some, such as cool and spring, plateau or even go both up and down in :math:`L^*` space. Data that is being represented in a region of the colormap that is at a plateau will lead to a perception of the data all having the same value (SHOW EXAMPLE?). + +For the Diverging maps, we want to have monotonically increasing :math:`L^*` values up to a maximum, which should be close to :math:`L^*=100`, followed by monotonically decreasing :math:`L^*` values. We are looking for approximately equal minimum :math:`L^*` values at opposite ends of the colormap. Additionally, we might prefer a diverging colormap which has a rounded instead of pointed peak for retaining some spread of values around the critical point. By these measures, BrBG and RdBu are good options. coolwarm is a good option, but it doesn't span a wide range of :math:`L^*` values (see grayscale section). + + +:math:`L^*` function +==================== + +WHAT FUNCTION FOR :math:`L^*`? + + +References +========== + +- C. Ware +- M. Niccoli +- IBM paper +- More + +.. :mod:`matplotlib.pyplot` is a collection of command style functions +.. that make matplotlib work like MATLAB. +.. Each ``pyplot`` function makes +.. some change to a figure: eg, create a figure, create a plotting area +.. in a figure, plot some lines in a plotting area, decorate the plot +.. with labels, etc.... :mod:`matplotlib.pyplot` is stateful, in that it +.. keeps track of the current figure and plotting area, and the plotting +.. functions are directed to the current axes + +.. .. plot:: pyplots/pyplot_simple.py +.. :include-source: + +.. You may be wondering why the x-axis ranges from 0-3 and the y-axis +.. from 1-4. If you provide a single list or array to the +.. :func:`~matplotlib.pyplot.plot` command, matplotlib assumes it is a +.. sequence of y values, and automatically generates the x values for +.. you. Since python ranges start with 0, the default x vector has the +.. same length as y but starts with 0. Hence the x data are +.. ``[0,1,2,3]``. + +.. :func:`~matplotlib.pyplot.plot` is a versatile command, and will take +.. an arbitrary number of arguments. For example, to plot x versus y, +.. you can issue the command:: + +.. plt.plot([1,2,3,4], [1,4,9,16]) + +.. For every x, y pair of arguments, there is an optional third argument +.. which is the format string that indicates the color and line type of +.. the plot. The letters and symbols of the format string are from +.. MATLAB, and you concatenate a color string with a line style string. +.. The default format string is 'b-', which is a solid blue line. For +.. example, to plot the above with red circles, you would issue + +.. .. plot:: pyplots/pyplot_formatstr.py +.. :include-source: + +.. See the :func:`~matplotlib.pyplot.plot` documentation for a complete +.. list of line styles and format strings. The +.. :func:`~matplotlib.pyplot.axis` command in the example above takes a +.. list of ``[xmin, xmax, ymin, ymax]`` and specifies the viewport of the +.. axes. + +.. If matplotlib were limited to working with lists, it would be fairly +.. useless for numeric processing. Generally, you will use `numpy +.. `_ arrays. In fact, all sequences are +.. converted to numpy arrays internally. The example below illustrates a +.. plotting several lines with different format styles in one command +.. using arrays. + +.. .. plot:: pyplots/pyplot_three.py +.. :include-source: + +.. .. _controlling-line-properties: + +.. Controlling line properties +.. =========================== + +.. Lines have many attributes that you can set: linewidth, dash style, +.. antialiased, etc; see :class:`matplotlib.lines.Line2D`. There are +.. several ways to set line properties + +.. * Use keyword args:: + +.. plt.plot(x, y, linewidth=2.0) + + +.. * Use the setter methods of the ``Line2D`` instance. ``plot`` returns a list +.. of lines; eg ``line1, line2 = plot(x1,y1,x2,y2)``. Below I have only +.. one line so it is a list of length 1. I use tuple unpacking in the +.. ``line, = plot(x, y, 'o')`` to get the first element of the list:: + +.. line, = plt.plot(x, y, '-') +.. line.set_antialiased(False) # turn off antialising + +.. * Use the :func:`~matplotlib.pyplot.setp` command. The example below +.. uses a MATLAB-style command to set multiple properties +.. on a list of lines. ``setp`` works transparently with a list of objects +.. or a single object. You can either use python keyword arguments or +.. MATLAB-style string/value pairs:: + +.. lines = plt.plot(x1, y1, x2, y2) +.. # use keyword args +.. plt.setp(lines, color='r', linewidth=2.0) +.. # or MATLAB style string value pairs +.. plt.setp(lines, 'color', 'r', 'linewidth', 2.0) + + +.. Here are the available :class:`~matplotlib.lines.Line2D` properties. + +.. ====================== ================================================== +.. Property Value Type +.. ====================== ================================================== +.. alpha float +.. animated [True | False] +.. antialiased or aa [True | False] +.. clip_box a matplotlib.transform.Bbox instance +.. clip_on [True | False] +.. clip_path a Path instance and a Transform instance, a Patch +.. color or c any matplotlib color +.. contains the hit testing function +.. dash_capstyle [``'butt'`` | ``'round'`` | ``'projecting'``] +.. dash_joinstyle [``'miter'`` | ``'round'`` | ``'bevel'``] +.. dashes sequence of on/off ink in points +.. data (np.array xdata, np.array ydata) +.. figure a matplotlib.figure.Figure instance +.. label any string +.. linestyle or ls [ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'steps'`` | ...] +.. linewidth or lw float value in points +.. lod [True | False] +.. marker [ ``'+'`` | ``','`` | ``'.'`` | ``'1'`` | ``'2'`` | ``'3'`` | ``'4'`` ] +.. markeredgecolor or mec any matplotlib color +.. markeredgewidth or mew float value in points +.. markerfacecolor or mfc any matplotlib color +.. markersize or ms float +.. markevery [ None | integer | (startind, stride) ] +.. picker used in interactive line selection +.. pickradius the line pick selection radius +.. solid_capstyle [``'butt'`` | ``'round'`` | ``'projecting'``] +.. solid_joinstyle [``'miter'`` | ``'round'`` | ``'bevel'``] +.. transform a matplotlib.transforms.Transform instance +.. visible [True | False] +.. xdata np.array +.. ydata np.array +.. zorder any number +.. ====================== ================================================== + +.. To get a list of settable line properties, call the +.. :func:`~matplotlib.pyplot.setp` function with a line or lines +.. as argument + +.. .. sourcecode:: ipython + +.. In [69]: lines = plt.plot([1,2,3]) + +.. In [70]: plt.setp(lines) +.. alpha: float +.. animated: [True | False] +.. antialiased or aa: [True | False] +.. ...snip + +.. .. _multiple-figs-axes: + +.. Working with multiple figures and axes +.. ====================================== + + +.. MATLAB, and :mod:`~matplotlib.pyplot`, have the concept of the current +.. figure and the current axes. All plotting commands apply to the +.. current axes. The function :func:`~matplotlib.pyplot.gca` returns the +.. current axes (a :class:`matplotlib.axes.Axes` instance), and +.. :func:`~matplotlib.pyplot.gcf` returns the current figure +.. (:class:`matplotlib.figure.Figure` instance). Normally, you don't have +.. to worry about this, because it is all taken care of behind the +.. scenes. Below is a script to create two subplots. + +.. .. plot:: pyplots/pyplot_two_subplots.py +.. :include-source: + +.. The :func:`~matplotlib.pyplot.figure` command here is optional because +.. ``figure(1)`` will be created by default, just as a ``subplot(111)`` +.. will be created by default if you don't manually specify an axes. The +.. :func:`~matplotlib.pyplot.subplot` command specifies ``numrows, +.. numcols, fignum`` where ``fignum`` ranges from 1 to +.. ``numrows*numcols``. The commas in the ``subplot`` command are +.. optional if ``numrows*numcols<10``. So ``subplot(211)`` is identical +.. to ``subplot(2,1,1)``. You can create an arbitrary number of subplots +.. and axes. If you want to place an axes manually, ie, not on a +.. rectangular grid, use the :func:`~matplotlib.pyplot.axes` command, +.. which allows you to specify the location as ``axes([left, bottom, +.. width, height])`` where all values are in fractional (0 to 1) +.. coordinates. See :ref:`pylab_examples-axes_demo` for an example of +.. placing axes manually and :ref:`pylab_examples-subplots_demo` for an +.. example with lots-o-subplots. + + +.. You can create multiple figures by using multiple +.. :func:`~matplotlib.pyplot.figure` calls with an increasing figure +.. number. Of course, each figure can contain as many axes and subplots +.. as your heart desires:: + +.. import matplotlib.pyplot as plt +.. plt.figure(1) # the first figure +.. plt.subplot(211) # the first subplot in the first figure +.. plt.plot([1,2,3]) +.. plt.subplot(212) # the second subplot in the first figure +.. plt.plot([4,5,6]) + + +.. plt.figure(2) # a second figure +.. plt.plot([4,5,6]) # creates a subplot(111) by default + +.. plt.figure(1) # figure 1 current; subplot(212) still current +.. plt.subplot(211) # make subplot(211) in figure1 current +.. plt.title('Easy as 1,2,3') # subplot 211 title + +.. You can clear the current figure with :func:`~matplotlib.pyplot.clf` +.. and the current axes with :func:`~matplotlib.pyplot.cla`. If you find +.. this statefulness, annoying, don't despair, this is just a thin +.. stateful wrapper around an object oriented API, which you can use +.. instead (see :ref:`artist-tutorial`) + +.. If you are making a long sequence of figures, you need to be aware of one +.. more thing: the memory required for a figure is not completely +.. released until the figure is explicitly closed with +.. :func:`~matplotlib.pyplot.close`. Deleting all references to the +.. figure, and/or using the window manager to kill the window in which +.. the figure appears on the screen, is not enough, because pyplot +.. maintains internal references until :func:`~matplotlib.pyplot.close` +.. is called. + +.. .. _working-with-text: + +.. Working with text +.. ================= + +.. The :func:`~matplotlib.pyplot.text` command can be used to add text in +.. an arbitrary location, and the :func:`~matplotlib.pyplot.xlabel`, +.. :func:`~matplotlib.pyplot.ylabel` and :func:`~matplotlib.pyplot.title` +.. are used to add text in the indicated locations (see :ref:`text-intro` +.. for a more detailed example) + +.. .. plot:: pyplots/pyplot_text.py +.. :include-source: + + +.. All of the :func:`~matplotlib.pyplot.text` commands return an +.. :class:`matplotlib.text.Text` instance. Just as with with lines +.. above, you can customize the properties by passing keyword arguments +.. into the text functions or using :func:`~matplotlib.pyplot.setp`:: + +.. t = plt.xlabel('my data', fontsize=14, color='red') + +.. These properties are covered in more detail in :ref:`text-properties`. + + +.. Using mathematical expressions in text +.. -------------------------------------- + +.. matplotlib accepts TeX equation expressions in any text expression. +.. For example to write the expression :math:`\sigma_i=15` in the title, +.. you can write a TeX expression surrounded by dollar signs:: + +.. plt.title(r'$\sigma_i=15$') + +.. The ``r`` preceding the title string is important -- it signifies +.. that the string is a *raw* string and not to treat backslashes as +.. python escapes. matplotlib has a built-in TeX expression parser and +.. layout engine, and ships its own math fonts -- for details see +.. :ref:`mathtext-tutorial`. Thus you can use mathematical text across platforms +.. without requiring a TeX installation. For those who have LaTeX and +.. dvipng installed, you can also use LaTeX to format your text and +.. incorporate the output directly into your display figures or saved +.. postscript -- see :ref:`usetex-tutorial`. + + +.. Annotating text +.. --------------- + +.. The uses of the basic :func:`~matplotlib.pyplot.text` command above +.. place text at an arbitrary position on the Axes. A common use case of +.. text is to annotate some feature of the plot, and the +.. :func:`~matplotlib.pyplot.annotate` method provides helper +.. functionality to make annotations easy. In an annotation, there are +.. two points to consider: the location being annotated represented by +.. the argument ``xy`` and the location of the text ``xytext``. Both of +.. these arguments are ``(x,y)`` tuples. + +.. .. plot:: pyplots/pyplot_annotate.py +.. :include-source: + +.. In this basic example, both the ``xy`` (arrow tip) and ``xytext`` +.. locations (text location) are in data coordinates. There are a +.. variety of other coordinate systems one can choose -- see +.. :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for +.. details. More examples can be found in +.. :ref:`pylab_examples-annotation_demo`. From 8d15dec0003a8f2c75630c5d1295efd14da9f4fc Mon Sep 17 00:00:00 2001 From: "Kristen M. Thyng" Date: Sat, 12 Jul 2014 17:49:33 -0500 Subject: [PATCH 2/6] added colormaps guide to beginner guide --- doc/users/beginner.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/users/beginner.rst b/doc/users/beginner.rst index c895415c4ffd..b17fb5c650bb 100644 --- a/doc/users/beginner.rst +++ b/doc/users/beginner.rst @@ -20,6 +20,7 @@ Beginner's Guide legend_guide.rst annotations_guide.rst screenshots.rst + colormaps.rst From 29714636e41d538cf6d31cb39a707e4c8d17be61 Mon Sep 17 00:00:00 2001 From: "Kristen M. Thyng" Date: Fri, 18 Jul 2014 11:37:37 -0500 Subject: [PATCH 3/6] some more text to colormaps --- doc/users/colormaps.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/users/colormaps.rst b/doc/users/colormaps.rst index 2621187a8c89..ed3c5b392629 100644 --- a/doc/users/colormaps.rst +++ b/doc/users/colormaps.rst @@ -37,6 +37,10 @@ Some of the :math:`L^*` values from the Sequential2 plots are monotonically incr For the Diverging maps, we want to have monotonically increasing :math:`L^*` values up to a maximum, which should be close to :math:`L^*=100`, followed by monotonically decreasing :math:`L^*` values. We are looking for approximately equal minimum :math:`L^*` values at opposite ends of the colormap. Additionally, we might prefer a diverging colormap which has a rounded instead of pointed peak for retaining some spread of values around the critical point. By these measures, BrBG and RdBu are good options. coolwarm is a good option, but it doesn't span a wide range of :math:`L^*` values (see grayscale section). +Qualitative colormaps are not necessarily aimed at being perceptual maps, but looking at the lightness parameter can solidify that for us. The :math:`L^*` values move all over the place throughout the colormap, and are clearly not monotonically increasing. These would not be good options for use as perceptual colormaps. + +MISCELLANEOUS + :math:`L^*` function ==================== From 1354f36697c8b29759e4f0cf9447d6d01c9d3853 Mon Sep 17 00:00:00 2001 From: "Kristen M. Thyng" Date: Thu, 24 Jul 2014 14:04:54 -0500 Subject: [PATCH 4/6] added a bunch of stuff to my colormap info --- doc/users/colormaps.rst | 83 ++++++++++++++++++++++++++++++++--------- 1 file changed, 65 insertions(+), 18 deletions(-) diff --git a/doc/users/colormaps.rst b/doc/users/colormaps.rst index ed3c5b392629..777145ea972d 100644 --- a/doc/users/colormaps.rst +++ b/doc/users/colormaps.rst @@ -10,51 +10,98 @@ Overview The idea behind choosing a good colormap is to find a good representation in 3D colorspace for your data set. The best colormap for any given data set depends on many things including: -- Whether representing form or metric data (link to C. Ware paper and explain more) -- Your knowledge of the data set (*i.e.*, is there a critical value from which the other values deviate?) +- Whether representing form or metric data ([Ware]_) +- Your knowledge of the data set (*e.g.*, is there a critical value from which the other values deviate?) - If there is an intuitive color scheme for the parameter you are plotting - If there is a standard in the field the audience may be expecting -For many applications, a perceptual colormap is the best choice |---| one in which equal steps in data are perceived as equal steps in the color space. Researchers have found that the human brain perceives changes in the lightness parameter as changes in the data much better than, for example, changes in hue. Therefore, colormaps which have monotonically increasing lightness through the colormap will be better interpreted by the viewer. +For many applications, a perceptual colormap is the best choice --- one in which equal steps in data are perceived as equal steps in the color space. Researchers have found that the human brain perceives changes in the lightness parameter as changes in the data much better than, for example, changes in hue. Therefore, colormaps which have monotonically increasing lightness through the colormap will be better interpreted by the viewer. -Color can be represented in 3D space in various ways. One way to represent color is using CIELAB (CITE). In CIELAB, color space is represented by lightness, :math:`L^*`; red-green, :math:`a`; and yellow-blue, :math:`b`. The lightness parameter :math:`L^*` can then be used to learn more about how the matplotlib colormaps will be perceived by viewers. +Color can be represented in 3D space in various ways. One way to represent color is using CIELAB. In CIELAB, color space is represented by lightness, :math:`L^*`; red-green, :math:`a^*`; and yellow-blue, :math:`b^*`. The lightness parameter :math:`L^*` can then be used to learn more about how the matplotlib colormaps will be perceived by viewers. -Sequential and diverging colormaps -================================== +Classes of colormaps +==================== + +Colormaps are often split into several categories based on function (see, *e.g.*, [Moreland]_): -STUFF +1. Sequential: change in lightness and often saturation of color incrementally, often using a single hue; should be used for representing information that has ordering. +2. Diverging: change in lightness and possibly saturation of two different colors that meet in the middle at an unsaturated color; should be used when the information being plotted has a critical middle value, such as topography or when the data deviates around zero. +3. Qualitative: often are miscellaneous colors; should be used to represent information which does not have ordering or relationships. Lightness of matplotlib colormaps ================================= -.. plot:: users/plotting/colormaps/lightness.py +Here we examine the lightness values of the matplotlib colormaps. Note that some documentation on the colormaps is available ([colormaps]_). + +Sequential +---------- + +For the Sequential plots, the lightness value increases monotonically through the colormaps. This is good. Some of the :math:`L^*` values in the colormaps span from 0 to 100 (binary and the other grayscale), and others start around :math:`L^*=20`. Those that have a smaller range of :math:`L^*` will accordingly have a smaller perceptual range. Note also that the :math:`L^*` function varies amongst the colormaps: some are approximately linear in :math:`L^*` and others are more curved. + +Sequential2 +----------- -For the Sequential plots, the lightness value increases monotonically through the colormaps. This is good. Some of the :math:`L^*` values in the colormaps span from 0 to 100 (binary and the other grayscale), and others start around :math:`L^*=20`. +Many of the :math:`L^*` values from the Sequential2 plots are monotonically increasing, but some (autumn, cool, spring, and winter) plateau or even go both up and down in :math:`L^*` space. Others (afmhot, copper, gist_heat, and hot) have kinks in the :math:`L^*` functions. Data that is being represented in a region of the colormap that is at a plateau or kink will lead to a perception of banding of the data in those values in the colormap (see [mycarta_banding]_ for an excellent example of this). -Some of the :math:`L^*` values from the Sequential2 plots are monotonically increasing, but some, such as cool and spring, plateau or even go both up and down in :math:`L^*` space. Data that is being represented in a region of the colormap that is at a plateau will lead to a perception of the data all having the same value (SHOW EXAMPLE?). +Diverging +--------- -For the Diverging maps, we want to have monotonically increasing :math:`L^*` values up to a maximum, which should be close to :math:`L^*=100`, followed by monotonically decreasing :math:`L^*` values. We are looking for approximately equal minimum :math:`L^*` values at opposite ends of the colormap. Additionally, we might prefer a diverging colormap which has a rounded instead of pointed peak for retaining some spread of values around the critical point. By these measures, BrBG and RdBu are good options. coolwarm is a good option, but it doesn't span a wide range of :math:`L^*` values (see grayscale section). +For the Diverging maps, we want to have monotonically increasing :math:`L^*` values up to a maximum, which should be close to :math:`L^*=100`, followed by monotonically decreasing :math:`L^*` values. We are looking for approximately equal minimum :math:`L^*` values at opposite ends of the colormap. By these measures, BrBG and RdBu are good options. coolwarm is a good option, but it doesn't span a wide range of :math:`L^*` values (see grayscale section below). -Qualitative colormaps are not necessarily aimed at being perceptual maps, but looking at the lightness parameter can solidify that for us. The :math:`L^*` values move all over the place throughout the colormap, and are clearly not monotonically increasing. These would not be good options for use as perceptual colormaps. +Qualitative +----------- -MISCELLANEOUS +Qualitative colormaps are not aimed at being perceptual maps, but looking at the lightness parameter can verify that for us. The :math:`L^*` values move all over the place throughout the colormap, and are clearly not monotonically increasing. These would not be good options for use as perceptual colormaps. + +Miscellaneous +------------- + +Some of the miscellaneous colormaps have particular uses they have been created for. For example, gist_earth, ocean, and terrain all seem to be created for plotting topography (green/brown) and water depths (blue) together. We would expect to see a divergence in these colormaps, then, but multiple kinks may not be ideal, such as in gist_earth and terrain. CMRmap was created to convert well to grayscale, though it does appear to have some small kinks in :math:`L^*`. cubehelix was created to vary smoothly in both lightness and hue, but appears to have a small hump in the green hue area. + +The often-used jet colormap is included in this set of colormaps. We can see that the :math:`L^*` values vary widely throughout the colormap, making it a poor choice for representing data for viewers to see perceptually. See an extension on this idea at [mycarta_jet]_. + +.. plot:: users/plotting/colormaps/lightness.py :math:`L^*` function ==================== -WHAT FUNCTION FOR :math:`L^*`? +There are multiple approaches to finding the best function for :math:`L^*` across a colormap. Linear gives reasonable results (*e.g.*, [mycarta_banding]_, [mycarta_lablinear]_). However, the Weber-Fechner law, and more generally and recently, Stevens' Law, indicates that a logarithmic or geometric relationship might be better (see effort on this front at [mycarta_cubelaw]_). + +.. plot:: users/plotting/colormaps/Lfunction.py + + +Grayscale conversion +==================== + +Conversion to grayscale is important to pay attention to for printing publications that have color plots. If this is not paid attention to ahead of time, your readers may end up with indecipherable plots because the grayscale changes unpredictably through the colormap. + +Conversion to grayscale is done in many different ways [bw]_. Some of the better ones use a linear combination of the rgb values of a pixel, but weighted according to how we perceive color intensity. A nonlinear method of conversion to grayscale is to use the :math:`L^*` values of the pixels. In general, similar principles apply for this question as they do for presenting one's information perceptually; that is, if a colormap is chosen that has monotonically increasing in :math:`L^*` values, it will print in a reasonable manner to grayscale. + +.. plot:: users/plotting/colormaps/grayscale.py + + +Color vision deficiencies +========================= + +MORE References ========== -- C. Ware -- M. Niccoli -- IBM paper -- More +.. [Ware] http://ccom.unh.edu/sites/default/files/publications/Ware_1988_CGA_Color_sequences_univariate_maps.pdf +.. [Moreland] http://www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf +.. [colormaps] https://gist.github.com/endolith/2719900#id7 +.. [mycarta_banding] http://mycarta.wordpress.com/2012/10/14/the-rainbow-is-deadlong-live-the-rainbow-part-4-cie-lab-heated-body/ +.. [mycarta_jet] http://mycarta.wordpress.com/2012/10/06/the-rainbow-is-deadlong-live-the-rainbow-part-3/ +.. [mycarta_lablinear] http://mycarta.wordpress.com/2012/12/06/the-rainbow-is-deadlong-live-the-rainbow-part-5-cie-lab-linear-l-rainbow/ +.. [mycarta_cubelaw] http://mycarta.wordpress.com/2013/02/21/perceptual-rainbow-palette-the-method/ +.. [bw] http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/ +IBM paper +More .. :mod:`matplotlib.pyplot` is a collection of command style functions .. that make matplotlib work like MATLAB. From 11243ff76062a192dc6b2a19268207c54d878406 Mon Sep 17 00:00:00 2001 From: "Kristen M. Thyng" Date: Thu, 24 Jul 2014 14:58:24 -0500 Subject: [PATCH 5/6] finished up draft --- doc/users/colormaps.rst | 293 ++-------------------------------------- 1 file changed, 12 insertions(+), 281 deletions(-) diff --git a/doc/users/colormaps.rst b/doc/users/colormaps.rst index 777145ea972d..5d5039c59e08 100644 --- a/doc/users/colormaps.rst +++ b/doc/users/colormaps.rst @@ -19,11 +19,13 @@ For many applications, a perceptual colormap is the best choice --- one in which Color can be represented in 3D space in various ways. One way to represent color is using CIELAB. In CIELAB, color space is represented by lightness, :math:`L^*`; red-green, :math:`a^*`; and yellow-blue, :math:`b^*`. The lightness parameter :math:`L^*` can then be used to learn more about how the matplotlib colormaps will be perceived by viewers. +An excellent starting resource for learning about human perception of colormaps is from [IBM]_. + Classes of colormaps ==================== -Colormaps are often split into several categories based on function (see, *e.g.*, [Moreland]_): +Colormaps are often split into several categories based on their function (see, *e.g.*, [Moreland]_): 1. Sequential: change in lightness and often saturation of color incrementally, often using a single hue; should be used for representing information that has ordering. 2. Diverging: change in lightness and possibly saturation of two different colors that meet in the middle at an unsaturated color; should be used when the information being plotted has a critical middle value, such as topography or when the data deviates around zero. @@ -78,7 +80,9 @@ Grayscale conversion Conversion to grayscale is important to pay attention to for printing publications that have color plots. If this is not paid attention to ahead of time, your readers may end up with indecipherable plots because the grayscale changes unpredictably through the colormap. -Conversion to grayscale is done in many different ways [bw]_. Some of the better ones use a linear combination of the rgb values of a pixel, but weighted according to how we perceive color intensity. A nonlinear method of conversion to grayscale is to use the :math:`L^*` values of the pixels. In general, similar principles apply for this question as they do for presenting one's information perceptually; that is, if a colormap is chosen that has monotonically increasing in :math:`L^*` values, it will print in a reasonable manner to grayscale. +Conversion to grayscale is done in many different ways [bw]_. Some of the better ones use a linear combination of the rgb values of a pixel, but weighted according to how we perceive color intensity. A nonlinear method of conversion to grayscale is to use the :math:`L^*` values of the pixels. In general, similar principles apply for this question as they do for presenting one's information perceptually; that is, if a colormap is chosen that has monotonically increasing in :math:`L^*` values, it will print in a reasonable manner to grayscale. + +With this in mind, we see that the Sequential colormaps have reasonable representations in grayscale. Some of the Sequential2 colormaps have decent enough grayscale representations, though some (autumn, spring, summer, winter) have very little grayscale change. If a colormap like this was used in a plot and then the plot was printed to grayscale, a lot of the information may map to the same gray values. The Diverging colormaps mostly vary from darker gray on the outer edges to white in the middle. Some (PuOr and seismic) have noticably darker gray on one side than the other and therefore are not very symmetric. coolwarm has little range of gray scale and would print to a more uniform plot, losing a lot of detail. Note that overlaid, labeled contours could help differentiate between one side of the colormap vs. the other since color cannot be used once a plot is printed to grayscale. Many of the Qualitative and Miscellaneous colormaps, such as Accent, hsv, and jet, change from darker to lighter and back to darker gray throughout the colormap. This would make it impossible for a viewer to interpret the information in a plot once it is printed in grayscale. .. plot:: users/plotting/colormaps/grayscale.py @@ -86,7 +90,9 @@ Conversion to grayscale is done in many different ways [bw]_. Some of the better Color vision deficiencies ========================= -MORE +There is a lot of information available about color blindness available (*e.g.*, [colorblindness]_). Additionally, there are tools available to convert images to how they look for different types of color vision deficiencies (*e.g.*, [asp]_). + +The most common form of color vision deficiency involves differentiating between red and green. Thus, avoiding colormaps with both red and green will avoid many problems in general. References @@ -100,282 +106,7 @@ References .. [mycarta_lablinear] http://mycarta.wordpress.com/2012/12/06/the-rainbow-is-deadlong-live-the-rainbow-part-5-cie-lab-linear-l-rainbow/ .. [mycarta_cubelaw] http://mycarta.wordpress.com/2013/02/21/perceptual-rainbow-palette-the-method/ .. [bw] http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/ -IBM paper -More - -.. :mod:`matplotlib.pyplot` is a collection of command style functions -.. that make matplotlib work like MATLAB. -.. Each ``pyplot`` function makes -.. some change to a figure: eg, create a figure, create a plotting area -.. in a figure, plot some lines in a plotting area, decorate the plot -.. with labels, etc.... :mod:`matplotlib.pyplot` is stateful, in that it -.. keeps track of the current figure and plotting area, and the plotting -.. functions are directed to the current axes - -.. .. plot:: pyplots/pyplot_simple.py -.. :include-source: - -.. You may be wondering why the x-axis ranges from 0-3 and the y-axis -.. from 1-4. If you provide a single list or array to the -.. :func:`~matplotlib.pyplot.plot` command, matplotlib assumes it is a -.. sequence of y values, and automatically generates the x values for -.. you. Since python ranges start with 0, the default x vector has the -.. same length as y but starts with 0. Hence the x data are -.. ``[0,1,2,3]``. - -.. :func:`~matplotlib.pyplot.plot` is a versatile command, and will take -.. an arbitrary number of arguments. For example, to plot x versus y, -.. you can issue the command:: - -.. plt.plot([1,2,3,4], [1,4,9,16]) - -.. For every x, y pair of arguments, there is an optional third argument -.. which is the format string that indicates the color and line type of -.. the plot. The letters and symbols of the format string are from -.. MATLAB, and you concatenate a color string with a line style string. -.. The default format string is 'b-', which is a solid blue line. For -.. example, to plot the above with red circles, you would issue - -.. .. plot:: pyplots/pyplot_formatstr.py -.. :include-source: - -.. See the :func:`~matplotlib.pyplot.plot` documentation for a complete -.. list of line styles and format strings. The -.. :func:`~matplotlib.pyplot.axis` command in the example above takes a -.. list of ``[xmin, xmax, ymin, ymax]`` and specifies the viewport of the -.. axes. - -.. If matplotlib were limited to working with lists, it would be fairly -.. useless for numeric processing. Generally, you will use `numpy -.. `_ arrays. In fact, all sequences are -.. converted to numpy arrays internally. The example below illustrates a -.. plotting several lines with different format styles in one command -.. using arrays. - -.. .. plot:: pyplots/pyplot_three.py -.. :include-source: - -.. .. _controlling-line-properties: - -.. Controlling line properties -.. =========================== - -.. Lines have many attributes that you can set: linewidth, dash style, -.. antialiased, etc; see :class:`matplotlib.lines.Line2D`. There are -.. several ways to set line properties - -.. * Use keyword args:: - -.. plt.plot(x, y, linewidth=2.0) - - -.. * Use the setter methods of the ``Line2D`` instance. ``plot`` returns a list -.. of lines; eg ``line1, line2 = plot(x1,y1,x2,y2)``. Below I have only -.. one line so it is a list of length 1. I use tuple unpacking in the -.. ``line, = plot(x, y, 'o')`` to get the first element of the list:: - -.. line, = plt.plot(x, y, '-') -.. line.set_antialiased(False) # turn off antialising - -.. * Use the :func:`~matplotlib.pyplot.setp` command. The example below -.. uses a MATLAB-style command to set multiple properties -.. on a list of lines. ``setp`` works transparently with a list of objects -.. or a single object. You can either use python keyword arguments or -.. MATLAB-style string/value pairs:: - -.. lines = plt.plot(x1, y1, x2, y2) -.. # use keyword args -.. plt.setp(lines, color='r', linewidth=2.0) -.. # or MATLAB style string value pairs -.. plt.setp(lines, 'color', 'r', 'linewidth', 2.0) - - -.. Here are the available :class:`~matplotlib.lines.Line2D` properties. - -.. ====================== ================================================== -.. Property Value Type -.. ====================== ================================================== -.. alpha float -.. animated [True | False] -.. antialiased or aa [True | False] -.. clip_box a matplotlib.transform.Bbox instance -.. clip_on [True | False] -.. clip_path a Path instance and a Transform instance, a Patch -.. color or c any matplotlib color -.. contains the hit testing function -.. dash_capstyle [``'butt'`` | ``'round'`` | ``'projecting'``] -.. dash_joinstyle [``'miter'`` | ``'round'`` | ``'bevel'``] -.. dashes sequence of on/off ink in points -.. data (np.array xdata, np.array ydata) -.. figure a matplotlib.figure.Figure instance -.. label any string -.. linestyle or ls [ ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'steps'`` | ...] -.. linewidth or lw float value in points -.. lod [True | False] -.. marker [ ``'+'`` | ``','`` | ``'.'`` | ``'1'`` | ``'2'`` | ``'3'`` | ``'4'`` ] -.. markeredgecolor or mec any matplotlib color -.. markeredgewidth or mew float value in points -.. markerfacecolor or mfc any matplotlib color -.. markersize or ms float -.. markevery [ None | integer | (startind, stride) ] -.. picker used in interactive line selection -.. pickradius the line pick selection radius -.. solid_capstyle [``'butt'`` | ``'round'`` | ``'projecting'``] -.. solid_joinstyle [``'miter'`` | ``'round'`` | ``'bevel'``] -.. transform a matplotlib.transforms.Transform instance -.. visible [True | False] -.. xdata np.array -.. ydata np.array -.. zorder any number -.. ====================== ================================================== - -.. To get a list of settable line properties, call the -.. :func:`~matplotlib.pyplot.setp` function with a line or lines -.. as argument - -.. .. sourcecode:: ipython - -.. In [69]: lines = plt.plot([1,2,3]) - -.. In [70]: plt.setp(lines) -.. alpha: float -.. animated: [True | False] -.. antialiased or aa: [True | False] -.. ...snip - -.. .. _multiple-figs-axes: - -.. Working with multiple figures and axes -.. ====================================== - - -.. MATLAB, and :mod:`~matplotlib.pyplot`, have the concept of the current -.. figure and the current axes. All plotting commands apply to the -.. current axes. The function :func:`~matplotlib.pyplot.gca` returns the -.. current axes (a :class:`matplotlib.axes.Axes` instance), and -.. :func:`~matplotlib.pyplot.gcf` returns the current figure -.. (:class:`matplotlib.figure.Figure` instance). Normally, you don't have -.. to worry about this, because it is all taken care of behind the -.. scenes. Below is a script to create two subplots. - -.. .. plot:: pyplots/pyplot_two_subplots.py -.. :include-source: - -.. The :func:`~matplotlib.pyplot.figure` command here is optional because -.. ``figure(1)`` will be created by default, just as a ``subplot(111)`` -.. will be created by default if you don't manually specify an axes. The -.. :func:`~matplotlib.pyplot.subplot` command specifies ``numrows, -.. numcols, fignum`` where ``fignum`` ranges from 1 to -.. ``numrows*numcols``. The commas in the ``subplot`` command are -.. optional if ``numrows*numcols<10``. So ``subplot(211)`` is identical -.. to ``subplot(2,1,1)``. You can create an arbitrary number of subplots -.. and axes. If you want to place an axes manually, ie, not on a -.. rectangular grid, use the :func:`~matplotlib.pyplot.axes` command, -.. which allows you to specify the location as ``axes([left, bottom, -.. width, height])`` where all values are in fractional (0 to 1) -.. coordinates. See :ref:`pylab_examples-axes_demo` for an example of -.. placing axes manually and :ref:`pylab_examples-subplots_demo` for an -.. example with lots-o-subplots. - - -.. You can create multiple figures by using multiple -.. :func:`~matplotlib.pyplot.figure` calls with an increasing figure -.. number. Of course, each figure can contain as many axes and subplots -.. as your heart desires:: - -.. import matplotlib.pyplot as plt -.. plt.figure(1) # the first figure -.. plt.subplot(211) # the first subplot in the first figure -.. plt.plot([1,2,3]) -.. plt.subplot(212) # the second subplot in the first figure -.. plt.plot([4,5,6]) - - -.. plt.figure(2) # a second figure -.. plt.plot([4,5,6]) # creates a subplot(111) by default - -.. plt.figure(1) # figure 1 current; subplot(212) still current -.. plt.subplot(211) # make subplot(211) in figure1 current -.. plt.title('Easy as 1,2,3') # subplot 211 title - -.. You can clear the current figure with :func:`~matplotlib.pyplot.clf` -.. and the current axes with :func:`~matplotlib.pyplot.cla`. If you find -.. this statefulness, annoying, don't despair, this is just a thin -.. stateful wrapper around an object oriented API, which you can use -.. instead (see :ref:`artist-tutorial`) - -.. If you are making a long sequence of figures, you need to be aware of one -.. more thing: the memory required for a figure is not completely -.. released until the figure is explicitly closed with -.. :func:`~matplotlib.pyplot.close`. Deleting all references to the -.. figure, and/or using the window manager to kill the window in which -.. the figure appears on the screen, is not enough, because pyplot -.. maintains internal references until :func:`~matplotlib.pyplot.close` -.. is called. - -.. .. _working-with-text: - -.. Working with text -.. ================= - -.. The :func:`~matplotlib.pyplot.text` command can be used to add text in -.. an arbitrary location, and the :func:`~matplotlib.pyplot.xlabel`, -.. :func:`~matplotlib.pyplot.ylabel` and :func:`~matplotlib.pyplot.title` -.. are used to add text in the indicated locations (see :ref:`text-intro` -.. for a more detailed example) - -.. .. plot:: pyplots/pyplot_text.py -.. :include-source: - - -.. All of the :func:`~matplotlib.pyplot.text` commands return an -.. :class:`matplotlib.text.Text` instance. Just as with with lines -.. above, you can customize the properties by passing keyword arguments -.. into the text functions or using :func:`~matplotlib.pyplot.setp`:: - -.. t = plt.xlabel('my data', fontsize=14, color='red') - -.. These properties are covered in more detail in :ref:`text-properties`. - - -.. Using mathematical expressions in text -.. -------------------------------------- - -.. matplotlib accepts TeX equation expressions in any text expression. -.. For example to write the expression :math:`\sigma_i=15` in the title, -.. you can write a TeX expression surrounded by dollar signs:: - -.. plt.title(r'$\sigma_i=15$') - -.. The ``r`` preceding the title string is important -- it signifies -.. that the string is a *raw* string and not to treat backslashes as -.. python escapes. matplotlib has a built-in TeX expression parser and -.. layout engine, and ships its own math fonts -- for details see -.. :ref:`mathtext-tutorial`. Thus you can use mathematical text across platforms -.. without requiring a TeX installation. For those who have LaTeX and -.. dvipng installed, you can also use LaTeX to format your text and -.. incorporate the output directly into your display figures or saved -.. postscript -- see :ref:`usetex-tutorial`. - - -.. Annotating text -.. --------------- - -.. The uses of the basic :func:`~matplotlib.pyplot.text` command above -.. place text at an arbitrary position on the Axes. A common use case of -.. text is to annotate some feature of the plot, and the -.. :func:`~matplotlib.pyplot.annotate` method provides helper -.. functionality to make annotations easy. In an annotation, there are -.. two points to consider: the location being annotated represented by -.. the argument ``xy`` and the location of the text ``xytext``. Both of -.. these arguments are ``(x,y)`` tuples. - -.. .. plot:: pyplots/pyplot_annotate.py -.. :include-source: +.. [colorblindness] http://aspnetresources.com/tools/colorBlindness +.. [asp] http://aspnetresources.com/tools/colorBlindness +.. [IBM] http://www.research.ibm.com/people/l/lloydt/color/color.HTM -.. In this basic example, both the ``xy`` (arrow tip) and ``xytext`` -.. locations (text location) are in data coordinates. There are a -.. variety of other coordinate systems one can choose -- see -.. :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for -.. details. More examples can be found in -.. :ref:`pylab_examples-annotation_demo`. From 52d585a44cf40f93bea18f25285c638f5b288b62 Mon Sep 17 00:00:00 2001 From: "Kristen M. Thyng" Date: Mon, 28 Jul 2014 10:36:08 -0500 Subject: [PATCH 6/6] now with scripts actually included! --- doc/users/plotting/colormaps/Lfunction.py | 171 ++++++++++++++++++++++ doc/users/plotting/colormaps/grayscale.py | 81 ++++++++++ doc/users/plotting/colormaps/lightness.py | 131 +++++++++++++++++ 3 files changed, 383 insertions(+) create mode 100644 doc/users/plotting/colormaps/Lfunction.py create mode 100644 doc/users/plotting/colormaps/grayscale.py create mode 100644 doc/users/plotting/colormaps/lightness.py diff --git a/doc/users/plotting/colormaps/Lfunction.py b/doc/users/plotting/colormaps/Lfunction.py new file mode 100644 index 000000000000..5ed9f7151517 --- /dev/null +++ b/doc/users/plotting/colormaps/Lfunction.py @@ -0,0 +1,171 @@ +''' +Recreate Josef Albers plot illustrating the Weber-Fechner law and illustrate +with the binary matplotlib colormap, too. Trying to show the difference between +adding blackness to a color at different rates. +''' + +import numpy as np +import matplotlib.pyplot as plt +from skimage import io, color +import pdb +import matplotlib as mpl +from mpl_toolkits.mplot3d import Axes3D +from matplotlib import cm, colors + + +mpl.rcParams.update({'font.size': 20}) +mpl.rcParams['font.sans-serif'] = 'Arev Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Helvetica, Avant Garde, sans-serif' +mpl.rcParams['mathtext.fontset'] = 'custom' +mpl.rcParams['mathtext.cal'] = 'cursive' +mpl.rcParams['mathtext.rm'] = 'sans' +mpl.rcParams['mathtext.tt'] = 'monospace' +mpl.rcParams['mathtext.it'] = 'sans:italic' +mpl.rcParams['mathtext.bf'] = 'sans:bold' +mpl.rcParams['mathtext.sf'] = 'sans' +mpl.rcParams['mathtext.fallback_to_cm'] = 'True' + + +### Red, original Albers plot + +nrows = 5 + +# Start with red +red = np.array([np.hstack([np.ones((nrows,1)), np.zeros((nrows,2))])]) + +# Get basic red in LAB +lab_add = color.rgb2lab(red) +lab_geometric = lab_add.copy() + +# Alter successive rows with more black +k = 1 +for i in xrange(red.shape[1]): + # more blackness is closer to 0 than one, and in first column of LAB + lab_add[0,i,0] = lab_add[0,i,0] - 10*i + print i,k + if i != 0: + lab_geometric[0,i,0] = lab_geometric[0,i,0] - 10*k + k *= 2 + +# Change LAB back to RGB for plotting +rgb_add = red.copy() # only change red values +temp = color.lab2rgb(lab_add) +rgb_add[0,:,0] = temp[0,:,0] +rgb_geometric = red.copy() # only change red values +temp = color.lab2rgb(lab_geometric) +rgb_geometric[0,:,0] = temp[0,:,0] + +fig = plt.figure() +k = 1 +for i in xrange(red.shape[1]): + + # LHS: additive + ax1 = fig.add_subplot(nrows,2,i*2+1, axisbg=tuple(rgb_add[0,i,:])) + print tuple(lab_add[0,i,:])#, tuple(rgb_add[0,i,:]) + + # RHS: multiplicative + ax2 = fig.add_subplot(nrows,2,i*2+2, axisbg=tuple(rgb_geometric[0,i,:])) + print tuple(lab_geometric[0,i,:])#, tuple(rgb_geometric[0,i,:]) + + # ylabels + if i!=0: + ax1.set_ylabel(str(1*i)) + ax2.set_ylabel(str(k)) + k *= 2 + + # Turn off ticks + ax1.get_xaxis().set_ticks([]) + ax2.get_xaxis().set_ticks([]) + ax1.get_yaxis().set_ticks([]) + ax2.get_yaxis().set_ticks([]) + + # Turn off black edges + ax1.spines['right'].set_visible(False) + ax1.spines['top'].set_visible(False) + ax1.spines['bottom'].set_visible(False) + ax1.spines['left'].set_visible(False) + ax2.spines['right'].set_visible(False) + ax2.spines['top'].set_visible(False) + ax2.spines['bottom'].set_visible(False) + ax2.spines['left'].set_visible(False) + + +# common ylabel +ax1.text(-0.3, 3.8, 'Additional Parts Black', + rotation=90, transform=ax1.transAxes) + + +fig.subplots_adjust(hspace=0.0) +plt.show() + + +### Albers plot with linear scale black and white + +nrows = 5 +ncols = 2 + +x = np.linspace(0.0, 1.0, 100) +cmap = 'binary' + +# Get binary colormap entries for full 100 entries +rgb = cm.get_cmap(cmap)(x)[np.newaxis,:,:3] + +# Sample 100-entry rgb additively and geometrically +rgb_add = np.empty((1,nrows,3)) +rgb_geometric = np.empty((1,nrows,3)) + +k = 1 +di = 8 +I0 = 5 +for i in xrange(nrows): + # Do more blackness via increasing indices + rgb_add[:,i,:] = rgb[:,i*di+I0,:] + + if i != 0: + print i*di+I0, di*k+I0, (I0**(1./3)+i*di**(1./3))**3 + rgb_geometric[:,i,:] = rgb[:,I0+di*k,:] + k *= 2 + elif i==0: + print i*di+I0, I0, (I0**(1./3)+i*di**(1./3))**3 + rgb_geometric[:,i,:] = rgb[:,I0,:] + +lab_add = color.rgb2lab(rgb_add) +lab_geometric = color.rgb2lab(rgb_geometric) + +fig = plt.figure() +k = 1 +for i in xrange(nrows): + + # LHS: additive + ax1 = fig.add_subplot(nrows,ncols,i*2+1, axisbg=tuple(rgb_add[0,i,:])) + + # middle: multiplicative + ax2 = fig.add_subplot(nrows,ncols,i*2+2, axisbg=tuple(rgb_geometric[0,i,:])) + + # ylabels + if i!=0: + ax1.set_ylabel(str(1*i)) + ax2.set_ylabel(str(k)) + k *= 2 + + # Turn off ticks + ax1.get_xaxis().set_ticks([]) + ax2.get_xaxis().set_ticks([]) + ax1.get_yaxis().set_ticks([]) + ax2.get_yaxis().set_ticks([]) + + # Turn off black edges + ax1.spines['right'].set_visible(False) + ax1.spines['top'].set_visible(False) + ax1.spines['bottom'].set_visible(False) + ax1.spines['left'].set_visible(False) + ax2.spines['right'].set_visible(False) + ax2.spines['top'].set_visible(False) + ax2.spines['bottom'].set_visible(False) + ax2.spines['left'].set_visible(False) + +# common ylabel +ax1.text(-0.3, 4.0, 'Steps through map indices', + rotation=90, transform=ax1.transAxes) + +fig.subplots_adjust(hspace=0.0) +plt.show() diff --git a/doc/users/plotting/colormaps/grayscale.py b/doc/users/plotting/colormaps/grayscale.py new file mode 100644 index 000000000000..e8824eb56ac2 --- /dev/null +++ b/doc/users/plotting/colormaps/grayscale.py @@ -0,0 +1,81 @@ +''' +Show what matplotlib colormaps look like in grayscale. +Uses lightness L* as a proxy for grayscale value. +''' + +from skimage import io, color +import numpy as np +import matplotlib.pyplot as plt +from matplotlib import cm +import matplotlib as mpl +import pdb +from scipy.optimize import curve_fit + +mpl.rcParams.update({'font.size': 14}) +mpl.rcParams['font.sans-serif'] = 'Arev Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Helvetica, Avant Garde, sans-serif' +mpl.rcParams['mathtext.fontset'] = 'custom' +mpl.rcParams['mathtext.cal'] = 'cursive' +mpl.rcParams['mathtext.rm'] = 'sans' +mpl.rcParams['mathtext.tt'] = 'monospace' +mpl.rcParams['mathtext.it'] = 'sans:italic' +mpl.rcParams['mathtext.bf'] = 'sans:bold' +mpl.rcParams['mathtext.sf'] = 'sans' +mpl.rcParams['mathtext.fallback_to_cm'] = 'True' + +# Have colormaps separated into categories: http://matplotlib.org/examples/color/colormaps_reference.html + +cmaps = [('Sequential', ['binary', 'Blues', 'BuGn', 'BuPu', 'gist_yarg', + 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', + 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', + 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']), + ('Sequential2', ['afmhot', 'autumn', 'bone', 'cool', 'copper', + 'gist_gray', 'gist_heat', 'gray', 'hot', 'pink', + 'spring', 'summer', 'winter']), + ('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', + 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'seismic']), + ('Qualitative', ['Accent', 'Dark2', 'hsv', 'Paired', 'Pastel1', + 'Pastel2', 'Set1', 'Set2', 'Set3', 'spectral']), + ('Miscellaneous', ['gist_earth', 'gist_ncar', 'gist_rainbow', + 'gist_stern', 'jet', 'brg', 'CMRmap', 'cubehelix', + 'gnuplot', 'gnuplot2', 'ocean', 'rainbow', + 'terrain', 'flag', 'prism'])] + +# indices to step through colormap +x = np.linspace(0.0, 1.0, 100) + +nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps) +gradient = np.linspace(0, 1, 256) +gradient = np.vstack((gradient, gradient)) + +def plot_color_gradients(cmap_category, cmap_list): + fig, axes = plt.subplots(nrows=nrows, ncols=2) + fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.05) + fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6) + + for ax, name in zip(axes, cmap_list): + + # Get rgb values for colormap + rgb = cm.get_cmap(plt.get_cmap(name))(x)[np.newaxis,:,:3] + + # Get colormap in CIE LAB. We want the L here. + lab = color.rgb2lab(rgb) + L = lab[0,:,0] + L = np.float32(np.vstack((L, L, L))) + + ax[0].imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) + ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.) + pos = list(ax[0].get_position().bounds) + x_text = pos[0] - 0.01 + y_text = pos[1] + pos[3]/2. + fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) + + # Turn off *all* ticks & spines, not just the ones with colormaps. + for ax in axes: + ax[0].set_axis_off() + ax[1].set_axis_off() + + +for cmap_category, cmap_list in cmaps: + + plot_color_gradients(cmap_category, cmap_list) + diff --git a/doc/users/plotting/colormaps/lightness.py b/doc/users/plotting/colormaps/lightness.py new file mode 100644 index 000000000000..9b0e21e14fbd --- /dev/null +++ b/doc/users/plotting/colormaps/lightness.py @@ -0,0 +1,131 @@ +''' +For each colormap, plot the lightness parameter L* from CIELAB colorspace along the y axis vs index through the colormap. Colormaps are examined in categories as in the original matplotlib gallery of colormaps. +''' + +from skimage import io, color +import numpy as np +import matplotlib.pyplot as plt +from matplotlib import cm +import matplotlib as mpl +import pdb +from scipy.optimize import curve_fit + +mpl.rcParams.update({'font.size': 14}) +mpl.rcParams['font.sans-serif'] = 'Arev Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Helvetica, Avant Garde, sans-serif' +mpl.rcParams['mathtext.fontset'] = 'custom' +mpl.rcParams['mathtext.cal'] = 'cursive' +mpl.rcParams['mathtext.rm'] = 'sans' +mpl.rcParams['mathtext.tt'] = 'monospace' +mpl.rcParams['mathtext.it'] = 'sans:italic' +mpl.rcParams['mathtext.bf'] = 'sans:bold' +mpl.rcParams['mathtext.sf'] = 'sans' +mpl.rcParams['mathtext.fallback_to_cm'] = 'True' + +# Have colormaps separated into categories: http://matplotlib.org/examples/color/colormaps_reference.html + +cmaps = [('Sequential', ['binary', 'Blues', 'BuGn', 'BuPu', 'gist_yarg', + 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', + 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', + 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']), + ('Sequential2', ['afmhot', 'autumn', 'bone', 'cool', 'copper', + 'gist_gray', 'gist_heat', 'gray', 'hot', 'pink', + 'spring', 'summer', 'winter']), + ('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', + 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'seismic']), + ('Qualitative', ['Accent', 'Dark2', 'hsv', 'Paired', 'Pastel1', + 'Pastel2', 'Set1', 'Set2', 'Set3', 'spectral']), + ('Miscellaneous', ['gist_earth', 'gist_ncar', 'gist_rainbow', + 'gist_stern', 'jet', 'brg', 'CMRmap', 'cubehelix', + 'gnuplot', 'gnuplot2', 'ocean', 'rainbow', + 'terrain', 'flag', 'prism'])] + +# indices to step through colormap +x = np.linspace(0.0, 1.0, 100) + +# Do plot +for cmap_category, cmap_list in cmaps: + + # Do subplots so that colormaps have enough space. 5 per subplot? + dsub = 5 # number of colormaps per subplot + if cmap_category == 'Diverging': # because has 13 colormaps + dsub = 6 + elif cmap_category == 'Sequential2': + dsub = 7 + elif cmap_category == 'Sequential': + dsub = 7 + nsubplots = int(np.ceil(len(cmap_list)/float(dsub))) + + fig = plt.figure(figsize=(11.5,4*nsubplots)) + + for i, subplot in enumerate(xrange(nsubplots)): + + locs = [] # locations for text labels + + ax = fig.add_subplot(nsubplots, 1, i+1) + # pdb.set_trace() + + for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]): + + # Get rgb values for colormap + rgb = cm.get_cmap(cmap)(x)[np.newaxis,:,:3] + + # Get colormap in CIE LAB. We want the L here. + lab = color.rgb2lab(rgb) + + # Plot colormap L values + # Do separately for each category so each plot can be pretty + # to make scatter markers change color along plot: http://stackoverflow.com/questions/8202605/matplotlib-scatterplot-colour-as-a-function-of-a-third-variable + if cmap_category=='Sequential': + dc = 0.6 # spacing between colormaps + ax.scatter(x+j*dc, lab[0,::-1,0], c=x, cmap=cmap + '_r', s=300, linewidths=0.) + if i==2: + ax.axis([-0.1,4.1,0,100]) + else: + ax.axis([-0.1,4.7,0,100]) + locs.append(x[-1]+j*dc) # store locations for colormap labels + + elif cmap_category=='Sequential2': + dc = 1.15 + ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.) + if i==0: + ax.axis([-0.1,8.1,0,100]) + else: + ax.axis([-0.1,7.0,0,100]) + locs.append(x[-1]+j*dc) # store locations for colormap labels + + elif cmap_category=='Diverging': + dc = 1.2 + ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.) + if i==0: + ax.axis([-0.1,7.1,0,100]) + else: + ax.axis([-0.1,6,0,100]) + locs.append(x[int(x.size/2.)]+j*dc) # store locations for colormap labels + + elif cmap_category=='Qualitative': + dc = 1.3 + ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.) + ax.axis([-0.1,6.3,0,100]) + locs.append(x[int(x.size/2.)]+j*dc) # store locations for colormap labels + + elif cmap_category=='Miscellaneous': + dc = 1.25 + ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.) + ax.axis([-0.1,6.1,0,100]) + locs.append(x[int(x.size/2.)]+j*dc) # store locations for colormap labels + + # Set up labels for colormaps + ax.xaxis.set_ticks_position('top') + ticker = mpl.ticker.FixedLocator(locs) + ax.xaxis.set_major_locator(ticker) + formatter = mpl.ticker.FixedFormatter(cmap_list[i*dsub:(i+1)*dsub]) + ax.xaxis.set_major_formatter(formatter) + labels = ax.get_xticklabels() + for label in labels: + label.set_rotation(60) + + ax.set_xlabel(cmap_category + ' colormaps', fontsize=22) + fig.text(-0.005, 0.55, 'Lightness $L^*$', fontsize=18, transform=fig.transFigure, rotation=90) + + fig.tight_layout(h_pad=0.05) + plt.show