Reset color cycle in Matplotlib

前端 未结 6 1084
北恋
北恋 2020-11-27 04:12

Say I have data about 3 trading strategies, each with and without transaction costs. I want to plot, on the same axes, the time series of each of the 6 variants (3 strategi

6条回答
  •  死守一世寂寞
    2020-11-27 04:42

    You can reset the colorcycle to the original with Axes.set_color_cycle. Looking at the code for this, there is a function to do the actual work:

    def set_color_cycle(self, clist=None):
        if clist is None:
            clist = rcParams['axes.color_cycle']
        self.color_cycle = itertools.cycle(clist
    

    And a method on the Axes which uses it:

    def set_color_cycle(self, clist):
        """
        Set the color cycle for any future plot commands on this Axes.
    
        *clist* is a list of mpl color specifiers.
        """
        self._get_lines.set_color_cycle(clist)
        self._get_patches_for_fill.set_color_cycle(clist)
    

    This basically means you can call the set_color_cycle with None as the only argument, and it will be replaced with the default cycle found in rcParams['axes.color_cycle'].

    I tried this with the following code and got the expected result:

    import matplotlib.pyplot as plt
    import numpy as np
    
    for i in range(3):
        plt.plot(np.arange(10) + i)
    
    # for Matplotlib version < 1.5
    plt.gca().set_color_cycle(None)
    # for Matplotlib version >= 1.5
    plt.gca().set_prop_cycle(None)
    
    for i in range(3):
        plt.plot(np.arange(10, 1, -1) + i)
    
    plt.show()
    

    Code output, showing the color cycling reset functionality

提交回复
热议问题