首页 > 解决方案 > 如何使最后绘制的 line2D 始终保持相同的颜色?

问题描述

我正在编写一个程序,用户可以在定义的轴上绘制函数。有什么办法可以使最后绘制的函数始终是固定颜色(比如说绿色)?

例如,下面的代码将多项式的次数作为输入,并绘制所有相同和更低次数的多项式。我想要一个调整,比如最后一个图(在这种情况下是最高次数的多项式)总是绿色的:

import numpy as np
import matplotlib.pyplot as plt

def plot_polynomials(highest_degree):

    x = np.arange(0,1,0.01)
    for degree in np.arange(1,highest_degree+1):
        coefficients = np.repeat(1,degree)
        label = 'degree={}'.format(degree)
        polynomial = np.polynomial.polynomial.polyval(x, coefficients)
        plt.plot(x, polynomial, label=label)

    plt.legend()
    plt.show()

plot_polynomials(6)

期待评论!

标签: pythonmatplotlibplotcolors

解决方案


这应该这样做:

def plot_polynomials(highest_degree):

    x = np.arange(0,1,0.01)
    for degree in np.arange(1,highest_degree+1):
        coefficients = np.repeat(1,degree)
        label = 'degree={}'.format(degree)
        colors=plt.rcParams['axes.prop_cycle'].by_key()['color']
        colors.pop(2) #Removing green from color cycle
        polynomial = np.polynomial.polynomial.polyval(x, coefficients)
        if degree==highest_degree:
            plt.plot(x, polynomial, label=label, color='g', lw=3)
        else:
            plt.plot(x, polynomial, label=label, color=colors[degree-1])
    plt.legend()
    plt.show()

plot_polynomials(6)

输出:

在此处输入图像描述

注意:用 使线条变粗lw,但这显然是可选的

编辑:从颜色循环中删除了绿色,所以只有一条绿线


推荐阅读