Skip to content

Commit 3b8a6ec

Browse files
committed
Merge pull request #6435 from tacaswell/backport_rgba_overhual
Merge pull request #6382 from anntzer/rgba-support
2 parents 5976e68 + 3281bcd commit 3b8a6ec

31 files changed

+383
-406
lines changed

doc/conf.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -333,5 +333,19 @@ def getapi(*args):
333333
sys.modules['sip'] = mocksip
334334
sys.modules['PyQt4'] = mockpyqt4
335335

336-
################# numpydoc config ####################
336+
# numpydoc config
337+
337338
numpydoc_show_class_members = False
339+
340+
# Skip deprecated members
341+
342+
def skip_deprecated(app, what, name, obj, skip, options):
343+
if skip:
344+
return skip
345+
skipped = {"matplotlib.colors": ["ColorConverter", "hex2color", "rgb2hex"]}
346+
skip_list = skipped.get(getattr(obj, "__module__", None))
347+
if skip_list is not None:
348+
return getattr(obj, "__name__", None) in skip_list
349+
350+
def setup(app):
351+
app.connect('autodoc-skip-member', skip_deprecated)

doc/users/colors.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ it can be provided as:
99

1010
* ``(r, g, b)`` tuples
1111
* ``(r, g, b, a)`` tuples
12-
* hex string, ex ``#OFOFOF``
12+
* hex string, ex ``#0F0F0F``, or ``#0F0F0F0F`` (with alpha channel)
1313
* float value between [0, 1] for gray level
1414
* One of ``{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}``
1515
* valid CSS4/X11 color names

doc/users/whats_new/rgba-support.rst

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Improved color conversion API and RGBA support
2+
----------------------------------------------
3+
4+
The :module:`~matplotlib.colors` gained a new color conversion API with
5+
full support for the alpha channel. The main public functions are
6+
:func:`~matplotlib.colors.is_color_like`, :func:`matplotlib.colors.to_rgba`,
7+
:func:`matplotlib.colors.to_rgba_array` and :func:`~matplotlib.colors.to_hex`.
8+
RGBA quadruplets are encoded in hex format as `#rrggbbaa`.
9+
10+
A side benefit is that the Qt options editor now allows setting the alpha
11+
channel of the artists as well.

examples/api/collections_demo.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@
1818
'''
1919

2020
import matplotlib.pyplot as plt
21-
from matplotlib import collections, transforms
22-
from matplotlib.colors import colorConverter
21+
from matplotlib import collections, colors, transforms
2322
import numpy as np
2423

2524
nverts = 50
@@ -39,7 +38,7 @@
3938
xyo = list(zip(xo, yo))
4039

4140
# Make a list of colors cycling through the default series.
42-
colors = [colorConverter.to_rgba(c)
41+
colors = [colors.to_rgba(c)
4342
for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]
4443

4544
fig, axes = plt.subplots(2, 2)

examples/color/named_colors.py

+13-28
Original file line numberDiff line numberDiff line change
@@ -11,36 +11,19 @@
1111

1212
import numpy as np
1313
import matplotlib.pyplot as plt
14-
from matplotlib import colors
14+
from matplotlib import colors as mcolors
1515

1616

17-
colors_ = list(six.iteritems(colors.cnames))
18-
19-
# Add the single letter colors.
20-
for name, rgb in six.iteritems(colors.ColorConverter.colors):
21-
hex_ = colors.rgb2hex(rgb)
22-
colors_.append((name, hex_))
23-
24-
# Transform to hex color values.
25-
hex_ = [color[1] for color in colors_]
26-
# Get the rgb equivalent.
27-
rgb = [colors.hex2color(color) for color in hex_]
28-
# Get the hsv equivalent.
29-
hsv = [colors.rgb_to_hsv(color) for color in rgb]
30-
31-
# Split the hsv values to sort.
32-
hue = [color[0] for color in hsv]
33-
sat = [color[1] for color in hsv]
34-
val = [color[2] for color in hsv]
35-
36-
# Get the color names by themselves.
37-
names = [color[0] for color in colors_]
17+
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
3818

3919
# Sort by hue, saturation, value and name.
40-
ind = np.lexsort((names, val, sat, hue))
41-
sorted_colors = [colors_[i] for i in ind]
20+
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
21+
for name, color in colors.items())
22+
23+
# Get the sorted color names.
24+
sorted_names = [name for hsv, name in by_hsv]
4225

43-
n = len(sorted_colors)
26+
n = len(sorted_names)
4427
ncols = 4
4528
nrows = int(np.ceil(1. * n / ncols))
4629

@@ -53,7 +36,7 @@
5336
# col width
5437
w = X / ncols
5538

56-
for i, (name, color) in enumerate(sorted_colors):
39+
for i, name in enumerate(sorted_names):
5740
col = i % ncols
5841
row = int(i / ncols)
5942
y = Y - (row * h) - h
@@ -68,8 +51,10 @@
6851

6952
# Add extra black line a little bit thicker to make
7053
# clear colors more visible.
71-
ax.hlines(y, xi_line, xf_line, color='black', linewidth=(h * 0.7))
72-
ax.hlines(y + h * 0.1, xi_line, xf_line, color=color, linewidth=(h * 0.6))
54+
ax.hlines(
55+
y, xi_line, xf_line, color='black', linewidth=(h * 0.7))
56+
ax.hlines(
57+
y + h * 0.1, xi_line, xf_line, color=colors[name], linewidth=(h * 0.6))
7358

7459
ax.set_xlim(0, X)
7560
ax.set_ylim(0, Y)

examples/event_handling/lasso_demo.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,17 @@
77
usable as is). There will be some refinement of the API.
88
"""
99
from matplotlib.widgets import Lasso
10-
from matplotlib.colors import colorConverter
1110
from matplotlib.collections import RegularPolyCollection
12-
from matplotlib import path
11+
from matplotlib import colors as mcolors, path
1312

1413
import matplotlib.pyplot as plt
1514
from numpy import nonzero
1615
from numpy.random import rand
1716

1817

1918
class Datum(object):
20-
colorin = colorConverter.to_rgba('red')
21-
colorout = colorConverter.to_rgba('blue')
19+
colorin = mcolors.to_rgba("red")
20+
colorout = mcolors.to_rgba("blue")
2221

2322
def __init__(self, x, y, include=False):
2423
self.x = x

examples/mplot3d/polys3d_demo.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from mpl_toolkits.mplot3d import Axes3D
22
from matplotlib.collections import PolyCollection
3-
from matplotlib.colors import colorConverter
43
import matplotlib.pyplot as plt
4+
from matplotlib import colors as mcolors
55
import numpy as np
66

77

@@ -10,7 +10,7 @@
1010

1111

1212
def cc(arg):
13-
return colorConverter.to_rgba(arg, alpha=0.6)
13+
return mcolors.to_rgba(arg, alpha=0.6)
1414

1515
xs = np.arange(0, 10, 0.4)
1616
verts = []

examples/pylab_examples/colours.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@
44
Some simple functions to generate colours.
55
"""
66
import numpy as np
7-
from matplotlib.colors import colorConverter
7+
from matplotlib import colors as mcolors
88

99

1010
def pastel(colour, weight=2.4):
1111
""" Convert colour into a nice pastel shade"""
12-
rgb = np.asarray(colorConverter.to_rgb(colour))
12+
rgb = np.asarray(mcolors.to_rgba(colour)[:3])
1313
# scale colour
1414
maxc = max(rgb)
1515
if maxc < 1.0 and maxc > 0:

examples/pylab_examples/demo_ribbon_box.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class RibbonBox(object):
1818
nx = original_image.shape[1]
1919

2020
def __init__(self, color):
21-
rgb = matplotlib.colors.colorConverter.to_rgb(color)
21+
rgb = matplotlib.colors.to_rgba(color)[:3]
2222

2323
im = np.empty(self.original_image.shape,
2424
self.original_image.dtype)

examples/pylab_examples/line_collection.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import matplotlib.pyplot as plt
22
from matplotlib.collections import LineCollection
3-
from matplotlib.colors import colorConverter
3+
from matplotlib import colors as mcolors
44

55
import numpy as np
66

@@ -30,7 +30,7 @@
3030
# where onoffseq is an even length tuple of on and off ink in points.
3131
# If linestyle is omitted, 'solid' is used
3232
# See matplotlib.collections.LineCollection for more information
33-
colors = [colorConverter.to_rgba(c)
33+
colors = [mcolors.to_rgba(c)
3434
for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]
3535

3636
line_segments = LineCollection(segs, linewidths=(0.5, 1, 1.5, 2),

examples/widgets/menu.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow',
1717
self.bgcolor = bgcolor
1818
self.alpha = alpha
1919

20-
self.labelcolor_rgb = colors.colorConverter.to_rgb(labelcolor)
21-
self.bgcolor_rgb = colors.colorConverter.to_rgb(bgcolor)
20+
self.labelcolor_rgb = colors.to_rgba(labelcolor)[:3]
21+
self.bgcolor_rgb = colors.to_rgba(bgcolor)[:3]
2222

2323

2424
class MenuItem(artist.Artist):

lib/matplotlib/_color_data.py

+12
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@
33

44
from matplotlib.externals import six
55

6+
7+
BASE_COLORS = {
8+
'b': (0, 0, 1),
9+
'g': (0, 0.5, 0),
10+
'r': (1, 0, 0),
11+
'c': (0, 0.75, 0.75),
12+
'm': (0.75, 0, 0.75),
13+
'y': (0.75, 0.75, 0),
14+
'k': (0, 0, 0),
15+
'w': (1, 1, 1)}
16+
17+
618
# This mapping of color names -> hex values is taken from
719
# a survey run by Randel Monroe see:
820
# http://blog.xkcd.com/2010/05/03/color-survey-results/

lib/matplotlib/axes/_axes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -2065,7 +2065,7 @@ def make_iterable(x):
20652065
if color is None:
20662066
color = [None] * nbars
20672067
else:
2068-
color = list(mcolors.colorConverter.to_rgba_array(color))
2068+
color = list(mcolors.to_rgba_array(color))
20692069
if len(color) == 0: # until to_rgba_array is changed
20702070
color = [[0, 0, 0, 0]]
20712071
if len(color) < nbars:
@@ -2074,7 +2074,7 @@ def make_iterable(x):
20742074
if edgecolor is None:
20752075
edgecolor = [None] * nbars
20762076
else:
2077-
edgecolor = list(mcolors.colorConverter.to_rgba_array(edgecolor))
2077+
edgecolor = list(mcolors.to_rgba_array(edgecolor))
20782078
if len(edgecolor) == 0: # until to_rgba_array is changed
20792079
edgecolor = [[0, 0, 0, 0]]
20802080
if len(edgecolor) < nbars:
@@ -3843,7 +3843,7 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
38433843
co = kwargs.pop('color', None)
38443844
if co is not None:
38453845
try:
3846-
mcolors.colorConverter.to_rgba_array(co)
3846+
mcolors.to_rgba_array(co)
38473847
except ValueError:
38483848
raise ValueError("'color' kwarg must be an mpl color"
38493849
" spec or sequence of color specs.\n"
@@ -6050,7 +6050,7 @@ def _normalize_input(inp, ename='input'):
60506050
if color is None:
60516051
color = [self._get_lines.get_next_color() for i in xrange(nx)]
60526052
else:
6053-
color = mcolors.colorConverter.to_rgba_array(color)
6053+
color = mcolors.to_rgba_array(color)
60546054
if len(color) != nx:
60556055
raise ValueError("color kwarg must have one color per dataset")
60566056

lib/matplotlib/axes/_base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def _process_plot_format(fmt):
6868

6969
# Is fmt just a colorspec?
7070
try:
71-
color = mcolors.colorConverter.to_rgb(fmt)
71+
color = mcolors.to_rgba(fmt)
7272

7373
# We need to differentiate grayscale '1.0' from tri_down marker '1'
7474
try:
@@ -112,14 +112,14 @@ def _process_plot_format(fmt):
112112
raise ValueError(
113113
'Illegal format string "%s"; two marker symbols' % fmt)
114114
marker = c
115-
elif c in mcolors.colorConverter.colors:
115+
elif c in mcolors.get_named_colors_mapping():
116116
if color is not None:
117117
raise ValueError(
118118
'Illegal format string "%s"; two color symbols' % fmt)
119119
color = c
120120
elif c == 'C' and i < len(chars) - 1:
121121
color_cycle_number = int(chars[i + 1])
122-
color = mcolors.colorConverter._get_nth_color(color_cycle_number)
122+
color = mcolors.to_rgba("C{}".format(color_cycle_number))
123123
i += 1
124124
else:
125125
raise ValueError(
@@ -3636,7 +3636,7 @@ def set_cursor_props(self, *args):
36363636
lw, c = args
36373637
else:
36383638
raise ValueError('args must be a (linewidth, color) tuple')
3639-
c = mcolors.colorConverter.to_rgba(c)
3639+
c = mcolors.to_rgba(c)
36403640
self._cursorProps = lw, c
36413641

36423642
def get_children(self):

lib/matplotlib/backend_bases.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1022,11 +1022,11 @@ def set_foreground(self, fg, isRGBA=False):
10221022
if self._forced_alpha and isRGBA:
10231023
self._rgb = fg[:3] + (self._alpha,)
10241024
elif self._forced_alpha:
1025-
self._rgb = colors.colorConverter.to_rgba(fg, self._alpha)
1025+
self._rgb = colors.to_rgba(fg, self._alpha)
10261026
elif isRGBA:
10271027
self._rgb = fg
10281028
else:
1029-
self._rgb = colors.colorConverter.to_rgba(fg)
1029+
self._rgb = colors.to_rgba(fg)
10301030

10311031
def set_graylevel(self, frac):
10321032
"""

lib/matplotlib/backends/backend_gtk.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,11 @@ def fn_name(): return sys._getframe(1).f_code.co_name
3535

3636
from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK
3737
from matplotlib.cbook import is_string_like, is_writable_file_like
38-
from matplotlib.colors import colorConverter
3938
from matplotlib.figure import Figure
4039
from matplotlib.widgets import SubplotTool
4140

42-
from matplotlib import lines
43-
from matplotlib import markers
44-
from matplotlib import cbook
45-
from matplotlib import verbose
46-
from matplotlib import rcParams
41+
from matplotlib import (
42+
cbook, colors as mcolors, lines, markers, rcParams, verbose)
4743

4844
backend_version = "%d.%d.%d" % gtk.pygtk_version
4945

@@ -1003,13 +999,13 @@ def on_combobox_lineprops_changed(self, item):
1003999
if marker is None: marker = 'None'
10041000
self.cbox_markers.set_active(self.markerd[marker])
10051001

1006-
r,g,b = colorConverter.to_rgb(line.get_color())
1007-
color = gtk.gdk.Color(*[int(val*65535) for val in (r,g,b)])
1002+
rgba = mcolors.to_rgba(line.get_color())
1003+
color = gtk.gdk.Color(*[int(val*65535) for val in rgba[:3]])
10081004
button = self.wtree.get_widget('colorbutton_linestyle')
10091005
button.set_color(color)
10101006

1011-
r,g,b = colorConverter.to_rgb(line.get_markerfacecolor())
1012-
color = gtk.gdk.Color(*[int(val*65535) for val in (r,g,b)])
1007+
rgba = mcolors.to_rgba(line.get_markerfacecolor())
1008+
color = gtk.gdk.Color(*[int(val*65535) for val in rgba[:3]])
10131009
button = self.wtree.get_widget('colorbutton_markerface')
10141010
button.set_color(color)
10151011
self._updateson = True

lib/matplotlib/backends/backend_gtk3.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,10 @@ def fn_name(): return sys._getframe(1).f_code.co_name
3636
from matplotlib import backend_tools
3737

3838
from matplotlib.cbook import is_string_like, is_writable_file_like
39-
from matplotlib.colors import colorConverter
4039
from matplotlib.figure import Figure
4140
from matplotlib.widgets import SubplotTool
4241

43-
from matplotlib import lines
44-
from matplotlib import cbook
45-
from matplotlib import verbose
46-
from matplotlib import rcParams
42+
from matplotlib import cbook, colors as mcolors, lines, verbose, rcParams
4743

4844
backend_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_micro_version(), Gtk.get_minor_version())
4945

0 commit comments

Comments
 (0)