gpt4 book ai didi

python - 为什么在为错误栏定义 "capsize"时会得到无效的 RGBA 参数 ValueError?

转载 作者:行者123 更新时间:2023-12-04 17:36:35 25 4
gpt4 key购买 nike

我正在尝试绘制水平条形图及其相应的误差条,但是,当我定义 capsize 时,我得到一个 ValueError: Invalid RGBA 参数。我在 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']

最佳答案

目前无法通过 bar API 创建多色瓶盖。 ( #14480 )

黑客将使用以下功能

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

关于python - 为什么在为错误栏定义 "capsize"时会得到无效的 RGBA 参数 ValueError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56490293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com