将颜色列表传递给pandas .p​​lot

时间:2018-03-20 04:46:54

标签: python pandas plot colors

我想从数据框绘制线图,每列一行(列数不同)。 e.g。

In:
        import pandas as pd
        import matplotlib.pyplot as plt
        df=pd.DataFrame (index = range (1,6),columns=['a','b'])
        df['a'] = [1,1,1,1,1]
        df['b']=[5,5,5,5,5]
        df
Out:
            a   b
        1   1   5
        2   1   5
        3   1   5
        4   1   5
        5   1   5

我正在使用subplots,因为我想将其他图添加到相同的轴,颜色相同。我发送了.plot一份颜色列表:

fig,ax=plt.subplots()
colours = ['r', 'b','g','y','m','c'][0:len(df.columns)]
ax.plot(df,linestyle = '-',color=colours)
plt.show()

我收到ValueError: Invalid RGBA argument: ['r','b']个例外。完整的错误消息是:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\PYTHONprojects\venv\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    154     try:
--> 155         rgba = _colors_full_map.cache[c, alpha]
    156     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:\PYTHONprojects\venv\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    305                 pass
    306             else:
--> 307                 return printer(obj)
    308             # Finally look for special method names
    309             method = get_real_method(obj, self.print_method)

C:\PYTHONprojects\venv\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    226 
    227     if 'png' in formats:
--> 228         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    229     if 'retina' in formats or 'png2x' in formats:
    230         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

C:\PYTHONprojects\venv\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    117 
    118     bytes_io = BytesIO()
--> 119     fig.canvas.print_figure(bytes_io, **kw)
    120     data = bytes_io.getvalue()
    121     if fmt == 'svg':

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2208                     orientation=orientation,
   2209                     dryrun=True,
-> 2210                     **kwargs)
   2211                 renderer = self.figure._cachedRenderer
   2212                 bbox_inches = self.figure.get_tightbbox(renderer)

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    509 
    510     def print_png(self, filename_or_obj, *args, **kwargs):
--> 511         FigureCanvasAgg.draw(self)
    512         renderer = self.get_renderer()
    513         original_dpi = renderer.dpi

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    429             # if toolbar:
    430             #     toolbar.set_cursor(cursors.WAIT)
--> 431             self.figure.draw(self.renderer)
    432             # A GUI class may be need to update a window using this draw, so
    433             # don't forget to call the superclass.

C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   1473 
   1474             mimage._draw_list_compositing_images(
-> 1475                 renderer, self, artists, self.suppressComposite)
   1476 
   1477             renderer.close_group('figure')

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2605             renderer.stop_rasterizing()
   2606 
-> 2607         mimage._draw_list_compositing_images(renderer, self, artists)
   2608 
   2609         renderer.close_group('axes')

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

C:\PYTHONprojects\venv\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:\PYTHONprojects\venv\lib\site-packages\matplotlib\lines.py in draw(self, renderer)
    759                 self._set_gc_clip(gc)
    760 
--> 761                 ln_color_rgba = self._get_rgba_ln_color()
    762                 gc.set_foreground(ln_color_rgba, isRGBA=True)
    763                 gc.set_alpha(ln_color_rgba[3])

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\lines.py in _get_rgba_ln_color(self, alt)
   1260 
   1261     def _get_rgba_ln_color(self, alt=False):
-> 1262         return mcolors.to_rgba(self._color, self._alpha)
   1263 
   1264     # some aliases....

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    155         rgba = _colors_full_map.cache[c, alpha]
    156     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 157         rgba = _to_rgba_no_colorcycle(c, alpha)
    158         try:
    159             _colors_full_map.cache[c, alpha] = rgba

C:\PYTHONprojects\venv\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    206         # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
    207         # Test dimensionality to reject single floats.
--> 208         raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
    209     # Return a tuple to prevent the cached value from being modified.
    210     c = tuple(c.astype(float))

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

<Figure size 432x288 with 1 Axes>

我做错了什么?我应该如何传递颜色列表,每列一个?

1 个答案:

答案 0 :(得分:1)

matplotlib的plot函数不接受这样的颜色列表。但是,如果使用方法DataFrame.plot,则可以指定颜色。

df.plot(linestyle='-', color=colours, ax=ax)