python - matplotlib如何用定义的颜色绘制多条线?

标签 python matplotlib anaconda

当我用颜色绘图时出现错误,没有它也能正常工作。我的线条颜色需要限制为 2 个定义的值。

这在 Jupyter Notebook 中有效

import random
xStart = random.sample(range(1, 10), 6)
xStart.sort()
xEnd = [x + random.randint(1, 6) for x in xStart]
yval = list(range(1, 7))
colours = ['r']*6
colours[1] = 'b'
print(xStart)
print(xEnd)
print(yval)
print(colours)
f, ax1 = plt.subplots(figsize=(6,4))
ax1.plot([xStart,xEnd], [yval,yval], '-', linewidth=1) #, color=colours)
plt.show()

Multiple line segments

这不起作用。 如果我取消注释颜色参数,代码会抛出一个(详细的)错误。虽然我可以在循环中绘制每个线段并将每个线段着色为红色或蓝色,但我认为它会比下面的代码慢。在这个玩具示例中,我有 6 条线,但实际上我有 12,000 条线,循环中一次绘制一条线需要几分钟。

我认为该错误与我的颜色参数的大小有关;它可能期望 1 个(内部一次),而我提供的是 6 个列表。

import random
xStart = random.sample(range(1, 10), 6)
xStart.sort()
xEnd = [x + random.randint(1, 6) for x in xStart]
yval = list(range(1, 7))
colours = ['r']*6
colours[1] = 'b'
print(xStart)
print(xEnd)
print(yval)
print(colours)
f, ax1 = plt.subplots(figsize=(6,4))
ax1.plot([xStart,xEnd], [yval,yval], '-', linewidth=1, color=colours)  #--> Only change from above code
plt.show()

TypeError Traceback (most recent call last) C:\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha) 131 try: --> 132 rgba = _colors_full_map.cache[c, alpha] 133 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) C:\Anaconda3\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)

C:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in (fig) 236 237 if 'png' in formats: --> 238 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 239 if 'retina' in formats or 'png2x' in formats: 240 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

C:\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs) 120 121 bytes_io = BytesIO() --> 122 fig.canvas.print_figure(bytes_io, **kw) 123 data = bytes_io.getvalue() 124 if fmt == 'svg':

C:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2214 orientation=orientation, 2215 dryrun=True, -> 2216 **kwargs) 2217 renderer = self.figure._cachedRenderer 2218 bbox_inches = self.figure.get_tightbbox(renderer)

C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs) 505 506 def print_png(self, filename_or_obj, *args, **kwargs): --> 507 FigureCanvasAgg.draw(self) 508 renderer = self.get_renderer() 509 original_dpi = renderer.dpi

C:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self) 428 # if toolbar: 429 # toolbar.set_cursor(cursors.WAIT) --> 430 self.figure.draw(self.renderer) 431 finally: 432 # if toolbar:

C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 53 renderer.start_filter() 54 ---> 55 return draw(artist, renderer, *args, **kwargs) 56 finally: 57 if artist.get_agg_filter() is not None:

C:\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer) 1297 1298
mimage._draw_list_compositing_images( -> 1299 renderer, self, artists, self.suppressComposite) 1300 1301
renderer.close_group('figure')

C:\Anaconda3\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

C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 53 renderer.start_filter() 54 ---> 55 return draw(artist, renderer, *args, **kwargs) 56 finally: 57 if artist.get_agg_filter() is not None:

C:\Anaconda3\lib\site-packages\matplotlib\axes_base.py in draw(self, renderer, inframe) 2435 renderer.stop_rasterizing()
2436 -> 2437 mimage._draw_list_compositing_images(renderer, self, artists) 2438 2439 renderer.close_group('axes')

C:\Anaconda3\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

C:\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 53 renderer.start_filter() 54 ---> 55 return draw(artist, renderer, *args, **kwargs) 56 finally: 57 if artist.get_agg_filter() is not None:

C:\Anaconda3\lib\site-packages\matplotlib\lines.py in draw(self, renderer) 765 self._set_gc_clip(gc) 766 --> 767 ln_color_rgba = self._get_rgba_ln_color() 768 gc.set_foreground(ln_color_rgba, isRGBA=True) 769 gc.set_alpha(ln_color_rgba[3])

C:\Anaconda3\lib\site-packages\matplotlib\lines.py in _get_rgba_ln_color(self, alt) 1267 1268 def _get_rgba_ln_color(self, alt=False): -> 1269 return mcolors.to_rgba(self._color, self._alpha) 1270 1271 # some aliases....

C:\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha) 132 rgba = _colors_full_map.cache[c, alpha] 133 except (KeyError, TypeError): # Not in cache, or unhashable. --> 134 rgba = _to_rgba_no_colorcycle(c, alpha) 135 try: 136 _colors_full_map.cache[c, alpha] = rgba

C:\Anaconda3\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha) 183 # float)andnp.array(...).astype(float)` all convert "0.5" to 0.5. 184 # Test dimensionality to reject single floats. --> 185 raise ValueError("Invalid RGBA argument: {!r}".format(orig_c)) 186 # Return a tuple to prevent the cached value from being modified. 187 c = tuple(c.astype(float))

ValueError: Invalid RGBA argument: ['r', 'b', 'r', 'r', 'r', 'r']

最佳答案

好的,感谢 Bazingaa 和此帖子,How to get different colored lines for different plots in a single figure?

...最终代码如下。

由于我使用一个 ax.plot() 命令绘制多条线,因此不会采用颜色参数。恕我直言,它应该是这样的,因为它在逻辑上是有意义的,并且应该是 matplotlib 的增强功能。尽管如此,这就是 Bazingaa 向我指出的解决方案。

对于那些感兴趣的人来说,正如预期的那样,与在循环中绘制 12K 行相比,此代码的运行速度确实要快得多(以便使用单独的 ax.plot() 命令一次绘制一条线并为其着色)。

import random
xStart = random.sample(range(1, 10), 6)
xStart.sort()
xEnd = [x + random.randint(1, 6) for x in xStart]
yval = list(range(1, 7))
colours = ['r']*6
colours[1] = 'b'
f, ax1 = plt.subplots(figsize=(6,4))
ax1.plot([xStart,xEnd], [yval,yval], '-', linewidth=1) #, color=colours)  #Leaving the color argument commented
#Add new code to colour after the fact
for idx,line in enumerate(ax1.lines):
        line.set_color(colours[idx])
plt.show()

关于python - matplotlib如何用定义的颜色绘制多条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953765/

相关文章:

python - : ImportError: "No module named ' graphlab'?如何解决

python - 如何相邻显示两个分布图?

python - 如何在 Python 上创建类?

python - 如何上传多个文件并在 S3 中组合它们

python - 替代 Matplotlib.colors.DivergingNorm

python - Anaconda: cannot import cv2 even though opencv is installed (how to install opencv3 for python3)

python - 使用 10 倍交叉验证时 sklearn 的特征大小

python - 与 sns.barplot 一起绘制表格

python - 减小具有许多重叠点和 alpha 的矢量化散点图磁盘上的大小

python - 安装 Visual Studio 19 时找不到 Visual Studio 17