matplotlib如何绘制具有定义颜色的多条线? [英] matplotlib how to plot multiple lines with defined colours?

查看:72
本文介绍了matplotlib如何绘制具有定义颜色的多条线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用颜色绘制时会出现错误,并且在没有颜色的情况下可以正常工作.我的线条颜色必须限制为2个定义的值.

I get an error when I plot with colours, and works fine without it. My line colours need to be restricted to 2 defined values.

这在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()

这不起作用.如果我取消对color参数的注释,则代码将引发一个(精心设计的)错误.虽然我可以画出一个循环中的每个线段并为每个红色或蓝色上色,但我认为它会比下面的代码慢.在这个玩具示例中,我有6条线,但实际上我有12,000条线,这花了几分钟,一次画一条线.

This does not work. If I uncomment the color argument, the code throws an (elaborate) error. While I can draw each line segment in a loop and colour each red or blue, I assume it will be slower than the below code. In this toy example I have 6 lines, but in reality I have 12,000 lines and it takes a few minutes, drawing one line at a time in a loop.

我认为错误与我的color参数的大小有关;它可能期望一次(内部一次),而我提供的是6.

I think the error is related to the size of my colour argument; it is likely expecting 1 (at a time internally) whereas I am providing a list of 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跟踪(最近一次调用最后)C:\ Anaconda3 \ lib \ site-packages \ matplotlib \ colors.pyto_rgba(c,alpha)131尝试:-> 132 rgba = _colors_full_map.cache [c,alpha]133(KeyError,TypeError)除外:#不在缓存中,或不可散列.

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:不可散列的类型:列表"

在处理上述异常期间,发生了另一个异常:

During handling of the above exception, another exception occurred:

ValueError跟踪(最近一次调用最后)C:\ Anaconda3 \ lib \ site-packages \ IPython \ core \ formatters.py在致电(自己,obj)339通过第340章-> 341返回打印机(obj)342#最后寻找特殊的方法名称343方法= get_real_method(obj,self.print_method)

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在(无花果)236237 if'png'格式:-> 238 png_formatter.for_type(图,lambda图:print_figure(fig,'png',** kwargs))239如果格式为'retina'或格式为'png2x':240 png_formatter.for_type(图,lambda图:retina_figure(fig,** kwargs))

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在print_figure(fig,fmt,bbox_inches,** kwargs)120121 bytes_io = BytesIO()-> 122图.canvas.print_figure(bytes_io,** kw)123数据= bytes_io.getvalue()124如果fmt =='svg':

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在print_figure(自身,文件名,dpi,面部颜色,边缘颜色,方向,格式,** kwargs)2214 direction = orientation,2215 dryrun = True,-> 2216 ** kwargs)2217渲染器= self.figure._cachedRenderer 2218 bbox_inches = self.figure.get_tightbbox(renderer)

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在print_png(自己,filename_or_obj,* args,** kwargs)505506 def print_png(自己,filename_or_obj,* args,** kwargs):-> 507 FigureCanvasAgg.draw()508渲染器= self.get_renderer()509 original_dpi = renderer.dpi

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在画(个体经营)428#如果工具栏:第429章-> 430 self.figure.draw(self.renderer)最终431:432#如果是工具栏:

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在draw_wrapper(艺术家,渲染器,* args,** kwargs)53 renderer.start_filter()54---> 55 return draw(艺术家,渲染器,* args,** kwargs)56最后:57如果artist.get_agg_filter()不是None:

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在draw(self,渲染器)1297 1298
mimage._draw_list_compositing_images(-> 1299渲染器,自我,艺术家,self.suppressComposite)1300 1301
renderer.close_group('figure')

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在_draw_list_compositing_images(渲染器,父级,艺术家,suppress_composite)136如果not_composite或not has_images:137位艺术家艺术家:-> 138 a.draw(渲染器)139其他:140#将任何相邻的图像合成在一起

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在draw_wrapper(艺术家,渲染器,* args,** kwargs)53 renderer.start_filter()54---> 55 return draw(艺术家,渲染器,* args,** kwargs)56最后:57如果artist.get_agg_filter()不是None:

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在draw(self,渲染器,内嵌)2435 renderer.stop_rasterizing()
2436-> 2437 mimage._draw_list_compositing_images(渲染器,自我,艺术家)2438 2439 renderer.close_group('axes')

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在_draw_list_compositing_images(渲染器,父级,艺术家,suppress_composite)136如果not_composite或not has_images:137位艺术家艺术家:-> 138 a.draw(渲染器)139其他:140#将任何相邻的图像合成在一起

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在draw_wrapper(艺术家,渲染器,* args,** kwargs)53 renderer.start_filter()54---> 55 return draw(艺术家,渲染器,* args,** kwargs)56最后:57如果artist.get_agg_filter()不是None:

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在draw(self,渲染器)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 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在_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#一些别名....

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....

to_rgba中的C:\ Anaconda3 \ lib \ site-packages \ matplotlib \ colors.py(c,α)132 rgba = _colors_full_map.cache [c,alpha]133除了(KeyError,TypeError):#不在缓存中,或不可散列.-> 134 rgba = _to_rgba_no_colorcycle(c,alpha)135尝试:136 _colors_full_map.cache [c,alpha] = rgba

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在_to_rgba_no_colorcycle(c,alpha)183#float) np.array(...).astype(float)都将"0.5"转换为0.5.184#测试尺寸以拒绝单个浮标.-> 185提高ValueError(无效的RGBA参数:{!r}".format(orig_c))186#返回一个元组,以防止修改缓存的值.187 c =元组(c.astype(float))

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:无效的RGBA参数:['r','b','r','r','r','r']

推荐答案

好的,感谢Bazingaa和该线程,

OK thanks to Bazingaa and this thread, How to get different colored lines for different plots in a single figure?

...最终代码如下.

...the final code is as follows.

由于我使用一个ax.plot()命令绘制了多条线,因此color参数将不可用.恕我直言,由于它在逻辑上是有意义的,因此应该是matplotlib的增强功能.尽管如此,这是Bazingaa指出的解决方案.

Since I am drawing multiple lines with one ax.plot() command, the colour argument will not take. IMHO it should since it logically makes sense and should be an enhancement matplotlib does. Nonetheless, here is the solution as Bazingaa pointed out to me.

对于感兴趣的人来说,与在循环中绘制12K线相比,此代码的确比在循环中运行LOT更快(以便使用单独的ax.plot()命令一次绘制和上色它们).

For those interested, as expected this code does run a LOT faster compared with drawing 12K lines in a loop (in order to draw & color them one at a time with individual ax.plot() commands).

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()

这篇关于matplotlib如何绘制具有定义颜色的多条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆