在 Matplotlib 中重置颜色循环 [英] Reset color cycle in Matplotlib

查看:35
本文介绍了在 Matplotlib 中重置颜色循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 3 种交易策略的数据,每种策略都有交易成本和没有交易成本.我想在相同的轴上绘制 6 个变体(3 个策略 * 2 个交易成本)中每一个的时间序列.我想用 alpha=1linewidth=1 绘制有交易成本"的线,而我想要用 alpha=0.25linewidth=5.但我希望每个策略的两个版本的颜色都相同.

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 strategies * 2 trading costs). I would like the "with transaction cost" lines to be plotted with alpha=1 and linewidth=1 while I want the "no transaction costs" to be plotted with alpha=0.25 and linewidth=5. But I would like the color to be the same for both versions of each strategy.

我想要一些类似的东西:

I would like something along the lines of:

fig, ax = plt.subplots(1, 1, figsize=(10, 10))

for c in with_transaction_frame.columns:
    ax.plot(with_transaction_frame[c], label=c, alpha=1, linewidth=1)

****SOME MAGIC GOES HERE TO RESET THE COLOR CYCLE

for c in no_transaction_frame.columns:
    ax.plot(no_transaction_frame[c], label=c, alpha=0.25, linewidth=5)

ax.legend()

在指定的行上放置什么适当的代码来重置颜色循环,以便在调用第二个循环时回到起点"?

What is the appropriate code to put on the indicated line to reset the color cycle so it is "back to the start" when the second loop is invoked?

推荐答案

您可以使用 Axes.set_color_cycle.查看此代码,有一个函数可以完成实际工作:

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

以及使用它的 Axes 上的方法:

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)

这基本上意味着您可以使用 None 作为唯一参数调用 set_color_cycle,它将被替换为 rcParams['axes.color_cycle'] 中的默认循环.

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

这篇关于在 Matplotlib 中重置颜色循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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