Why do I get an invalid RGBA argument ValueError when defining “capsize” to my error bars?

I am trying to plot horizontal bar plots with their corresponding error bars, however, when I define capsize I get a ValueError: Invalid RGBA argument. I am running the script in a Jupyter Notebook, but the error persists in a linux shell as well.

I should note that I want the colors of the bar plots and their error bars to match.

Looking at other questions here, it seems that this error is thrown when the shape of color is wrong, but I don’t see how this fixes my problem.
Here is the code to reproduce the error:

values = {0: [0.29, 0.21, 0.43],
          1: [0.16, 0.14, 0.21],
          2: [0.73, 0.11, 0.14]}

errors = {0: [0.13, 0.02, 0.08],
          1: [0.066, 0.08, 0.1],
          2: [0.21, 0.027, 0.078]}

fig, axes = plt.subplots(1, 3, figsize=(3,3))

colors=['#7bad10', '#103cad', '#ad109a']

for count, ax in enumerate(axes):

    xerr = [errors[x][count] for x in errors.keys()]

    ax.barh([0, 0.5, 1], 
            [values[x][count] for x in values.keys()], 
            [0.3, 0.3, 0.3], 
            color=colors, 
#             capsize=2,
            xerr=xerr, 
            error_kw = {
                'elinewidth': 1, 
                'ecolor' : colors}
            )

    if count != 0:
        ax.get_yaxis().set_visible(False) 

    ax.set_xlim([0, 1])

This code as it is now, works fine, but when I uncomment capsize it throws the error. If I comment the ecolor line, then I can use capsize without a problem, but I cannot define both of them.
How can I fix this? Thank you.

Also, here is a more detailed output of the error:

  Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x000001A1EB387620> (for post_execute):
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    173     try:
--> 174         rgba = _colors_full_map.cache[c, alpha]
    175     except (KeyError, TypeError):  # Not in cache, or unhashable.

TypeError: unhashable type: 'list'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110 
    111             # IPython >= 2

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\_pylab_helpers.py in draw_all(cls, force)
    130         for f_mgr in cls.get_all_fig_managers():
    131             if force or f_mgr.canvas.figure.stale:
--> 132                 f_mgr.canvas.draw_idle()
    133 
    134 atexit.register(Gcf.destroy_all)

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\backend_bases.py in draw_idle(self, *args, **kwargs)
   1897         if not self._is_idle_drawing:
   1898             with self._idle_draw_cntx():
-> 1899                 self.draw(*args, **kwargs)
   1900 
   1901     def draw_cursor(self, event):

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\lines.py in draw(self, renderer)
    779 
    780             ec_rgba = mcolors.to_rgba(
--> 781                 self.get_markeredgecolor(), self._alpha)
    782             fc_rgba = mcolors.to_rgba(
    783                 self._get_markerfacecolor(), self._alpha)

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    174         rgba = _colors_full_map.cache[c, alpha]
    175     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 176         rgba = _to_rgba_no_colorcycle(c, alpha)
    177         try:
    178             _colors_full_map.cache[c, alpha] = rgba

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    225         # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
    226         # Test dimensionality to reject single floats.
--> 227         raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
    228     # Return a tuple to prevent the cached value from being modified.
    229     c = tuple(c.astype(float))

ValueError: Invalid RGBA argument: ['#7bad10', '#103cad', '#ad109a']

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    173     try:
--> 174         rgba = _colors_full_map.cache[c, alpha]
    175     except (KeyError, TypeError):  # Not in cache, or unhashable.

TypeError: unhashable type: 'list'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
~\Anaconda3\envs\newDENSITY\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~\Anaconda3\envs\newDENSITY\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~\Anaconda3\envs\newDENSITY\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2047                         orientation=orientation,
   2048                         dryrun=True,
-> 2049                         **kwargs)
   2050                     renderer = self.figure._cachedRenderer
   2051                     bbox_artists = kwargs.pop("bbox_extra_artists", None)

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    508 
    509         """
--> 510         FigureCanvasAgg.draw(self)
    511         renderer = self.get_renderer()
    512 

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\lines.py in draw(self, renderer)
    779 
    780             ec_rgba = mcolors.to_rgba(
--> 781                 self.get_markeredgecolor(), self._alpha)
    782             fc_rgba = mcolors.to_rgba(
    783                 self._get_markerfacecolor(), self._alpha)

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    174         rgba = _colors_full_map.cache[c, alpha]
    175     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 176         rgba = _to_rgba_no_colorcycle(c, alpha)
    177         try:
    178             _colors_full_map.cache[c, alpha] = rgba

~\Anaconda3\envs\newDENSITY\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    225         # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
    226         # Test dimensionality to reject single floats.
--> 227         raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
    228     # Return a tuple to prevent the cached value from being modified.
    229     c = tuple(c.astype(float))

ValueError: Invalid RGBA argument: ['#7bad10', '#103cad', '#ad109a']
Enquirer: besi

||

Solution #1:

It is currently not possible to create multicolor caps through the bar API. (#14480)

A hack would be to use the following function

def colorize_errorbars(cont, colors, ax=None):
    ax = ax or plt.gca()
    scs = []
    for line in cont.errorbar.lines[1]:
        line.remove()
        sc = ax.scatter(*line.get_data(), c=colors, marker=line.get_marker(),
                               s=line.get_markersize()**2, zorder=3)
        scs.append(sc)
    cont.errorbar.lines = (cont.errorbar.lines[0], tuple(scs), cont.errorbar.lines[2])
    for col in cont.errorbar.lines[2]:
        col.set_color(colors)

e.g., like

fig, ax = plt.subplots( figsize=(3,3))

colors=['crimson', 'limegreen', 'indigo']

bars = ax.bar( [0,1,2], 
        [5,3,4],
        linewidth=2,
        color="papayawhip",
        edgecolor=colors,
        capsize=3,
        yerr=[1.5, 1, 1.5], 
        error_kw = { 'elinewidth': 2, }
        )

colorize_errorbars(bars, colors, ax)    

plt.show()

enter image description here

Respondent: besi

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.