如何使最后打印的线条2D始终保持相同的颜色?

2024-06-09 14:46:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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)

期待您的评论


Tags: 函数importplotasnp绘制plt次数
1条回答
网友
1楼 · 发布于 2024-06-09 14:46:08

这应该做到:

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)

输出:

enter image description here

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

编辑:从颜色循环中删除绿色,因此只有一条绿线

相关问题 更多 >