为什么我在定义误差棒的“capsize”时,会出现无效的RGBA参数ValueError错误?

3
我正在尝试绘制带有相应误差条的水平条形图,但是当我定义capsize时,我会得到一个ValueError: Invalid RGBA argument。我在Jupyter Notebook中运行脚本,但错误也在linux shell中持续存在。
我应该注意到,我希望条形图和它们的误差条的颜色匹配。
从这里查看其他问题,似乎当color的形状不正确时,会引发此错误,但我不知道如何解决我的问题。 以下是重现错误的代码:
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])

这段代码现在运行良好,但当我取消注释capsize时,它会抛出错误。如果我注释掉ecolor这一行,那么我就可以无问题地使用capsize,但是我不能同时定义两个。如何解决这个问题?谢谢。

此外,以下是更详细的错误输出:

  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']

我将此问题提交到问题跟踪器 - ImportanceOfBeingErnest
谢谢您的回复。目前,我已经通过在每个轴上添加ax.errorbar()并通过它添加caps来解决了我的问题。 - besi
1个回答

1

目前无法通过bar API创建多彩帽子。(#14480)

一个hack的方法是使用以下函数

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)

例如,像这样。
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


是的,那个方法可行。我自己解决的方法是(以你的示例为例)从ax.bar()调用中删除capsize、yerr和error_kw,并在代码末尾添加以下内容:for i in range(len(bars)): ax.errorbar([0,1,2][i], [5,3,4][i], yerr=[1.5, 1, 1.5][i], capsize=3, elinewidth=2, color=colors[i])希望这也可以。 - besi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接