【问题标题】:Plot multiple functions with the same properties in matplotlib在 matplotlib 中绘制具有相同属性的多个函数
【发布时间】:2016-06-22 21:26:19
【问题描述】:

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

问题是我尝试的所有图,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()

以上仅为简化示例。在实践中我有更多的函数和参数,所以循环颜色的解决方案不是很有帮助

【问题讨论】:

  • 我不明白为什么你不能硬编码情节语句中的颜色,如果你每次都想要相同的颜色:ax.plot(x,a*np.sin(x),x,a*np.cos(x), '-ks' ,label='trig a={}'.format(a))。请注意添加了'-ks':即黑色 (k) 实线 (-) 以及值所在的正方形 (s)。您可以将其更改为您想要的样式,并且每个绘图都将具有相同的样式。
  • 在原始问题中,每个参数显示超过 10 个函数,并且在迭代过程中显示了许多参数。硬编码颜色可以解决一些问题,但在某些情况下,我会用完颜色列表。另一个大问题是每个函数都会有一个我必须避免的关联图例。此外,我正在根据参数对函数图进行注释,这更加复杂。

标签: python matplotlib


【解决方案1】:

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

我不知道如何有条件地为艺术家设置标签,因此以下部分(if)是一个技巧,可以由对@987654325 内部工作有更多了解的人改进@。

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, '-',...

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

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2014-04-12
    相关资源
    最近更新 更多