Skip to main content
 首页 » 编程设计

python之在 matplotlib 中绘制具有相同属性的多个函数

2024年10月17日8davidwang456

我尝试可视化来自单个参数的多个函数。我需要对参数进行某种循环。我想为给定参数的所有绘制函数分配相同的颜色、图例等。

问题是我尝试的所有图,matplotlib 分配不同的颜色并总是给出标签。

基本上我想实现这样的目标:

import numpy as np 
import matplotlib.pyplot as plt 
def plot2():     
    fig, ax = plt.subplots() 
    x = np.arange(0,10,0.1) 
    ax.plot(x,1*np.sin(x),'b-') 
    ax.plot(x,1*np.cos(x),'b-',label='trig a={}'.format(1)) 
    ax.plot(x,2*np.sin(x),'g-') 
    ax.plot(x,2*np.cos(x),'g-',label='trig a={}'.format(2)) 
    ax.plot(x,3*np.sin(x),'r-') 
    ax.plot(x,3*np.cos(x),'r-',label='trig a={}'.format(3)) 
    ax.legend() 

但具有如下功能:

def plotTrig(): 
    fig, ax = plt.subplots() 
    x = np.arange(0,10,0.1) 
    for a in [1,2,3]: 
        ax.plot(x,a*np.sin(x),x,a*np.cos(x),label='trig a={}'.format(a)) 
    ax.legend() 

以上只是简化的例子。实际上我有更多的函数和参数,所以循环颜色的解决方案不是很有帮助

请您参考如下方法:

我想现在我明白你想要什么了。您永远不会用完颜色,因为 matplotlib 支持范围广泛的颜色定义。任何合法的 HTML 名称,任何 RGB 三元组,......

我不知道如何有条件地为艺术家设置标签,所以下面的部分(if)是一个 hack,可以由对matplotlib 的内部工作。

import numpy as np 
import matplotlib.pyplot as plt 
 
def my_sin(x, a): 
    return a * np.sin(x) 
 
def my_cos(x, a): 
    return a * np.cos(x) 
 
def my_tanh(x, a): 
    return np.tanh(x / a - 1) 
 
def plotTrig(x, data, colors, parameters): 
    fig, ax = plt.subplots() 
    for ind, a in enumerate(parameters): 
        for name, func in data.iteritems(): 
            if (name == 'sin'):  # or any other 
                ax.plot(x, func(x, a), '-', 
                        color=colors[ind], 
                        label='trig a={}'.format(a)) 
            else: 
                ax.plot(x, func(x, a), '-', 
                        color=colors[ind]) 
    ax.legend() 
 
 
if __name__ == '__main__': 
    # prepare data 
    x = np.arange(0,10,0.1) 
    data = {}  # dictionary to hold the values 
    data['sin'] = my_sin 
    data['cos'] = my_cos 
    data['tanh'] = my_tanh 
    # list to hold the colors for each parameter 
    colors = ['burlywood', 'r', '#0000FF', '0.25', (0.75, 0, 0.75)] 
    # parameters 
    parameters = [1, 2, 3, 4, 5] 
    plotTrig(x, data, colors, parameters) 
    plt.show() 

我们的想法是将不同的函数放在一个容器中,这样我们就可以遍历它们(列表也可以),然后为每个函数使用相同的颜色,但为每个参数使用不同的颜色。标签仅添加到一个带有 hacky if 语句的函数中。

如果我只是将字典值设置为函数的结果,我可以做得更简单:

data['sin'] = np.sin(x) 

然后绘制

ax.plot(x, a * func, '-',... 

重现您的示例,但您的参数只能应用于函数的结果。这样您就可以以任何可以表达为函数的方式使用它们。

结果: