【问题标题】:MatPlot Lib Parameters and For LoopsMatPlotLib 参数和 For 循环
【发布时间】:2020-11-01 22:04:19
【问题描述】:

与绘图和以下用户定义函数有关的两个问题。作为背景,这是我第一次看到 plt.plot 在 for 循环中调用,这样每个点都是单独绘制的。我习惯于看到整个数组作为参数传递,例如plt.plot(x, f(x))。我的第一个问题是迭代每个点并每次调用 plt.plot 有什么好处?与调用plt.plot(x, f(x)) 并通过一次所有点相比,使用此方法是否可以对绘图进行一些额外的控制?

我的第二个问题是关于下面函数中的样式参数。我不确定索引到包含单个字符的列表如何或为什么有效? styles = [‘b’] 是一个包含单个字符的列表。所以我的期望是,任何使用非 0 参数的切片/索引都会引发异常。换句话说,我希望当 for 循环索引超过 0(例如 styles[1], styles [2], 等)时,会引发异常。我错过了什么?

import numpy as np
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
%matplotlib inline

def f(x):
    return np.sin(x) + 0.5 * x

def create_plot(x, y, styles, labels, axlabels):
    plt.figure(figsize=(10, 6))
    for i in range(len(x)):
        plt.plot(x[i], y[i], styles[i], label=labels[i])
        plt.xlabel(axlabels[0])
        plt.ylabel(axlabels[1])
        plt.legend(loc=0)

x = np.linspace(-2 * np.pi, 2 * np.pi, 50)

create_plot([x], [f(x)], ['b'], ['f(x)'], ['x', 'f(x)'])

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

    您似乎混淆了全局参数x(一个点数组)和函数参数x(一个数组(点)列表)。所以,xs 都代表了一个完全不同的概念。下面的代码重命名函数参数以避免一些混淆。还有,现在pylab is usually replaced by matplotlib.

    该函数的主要思想是xystyleslabels 通常会有多个元素。这四个列表应该具有相同数量的元素。在原始示例中,每个元素只有一个。

    online documentation of the plot 命令对样式的参数字符串进行了广泛的概述。例如'b' 只是一条蓝线。 -r* 是红色的,每个顶点都有星星,用实线连接。 g: 表示绿色虚线。等等。

    这是一个绘制 3 个函数的示例:

    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    plt.style.use('seaborn')
    mpl.rcParams['font.family'] = 'serif'
    
    def f(x):
        return np.sin(x) + 0.5 * x
    
    def create_plot(xs, ys, styles, labels, axlabels):
        plt.figure(figsize=(10, 6))
        for i in range(len(xs)):
            plt.plot(xs[i], ys[i], styles[i], label=labels[i])
            plt.xlabel(axlabels[0])
            plt.ylabel(axlabels[1])
            plt.legend(loc=0)
    
    x = np.linspace(-2 * np.pi, 2 * np.pi, 50)
    create_plot([x, x, x], [f(x), np.cos(x), x * x / 20], ['b', '-r*', 'g:'],
                ['f(x)', 'cos(x)', 'x^2 / 20'], ['x', 'f(x)'])
    plt.show()
    

    【讨论】:

      【解决方案2】:

      在考虑了更多之后,我能够解决第二个问题。我没有意识到 [x] 是长度为 1 的列表,因此 for 循环仅迭代一次,因此与 styles = ['b'] 没有冲突,因为实现的 i 的唯一值是 0。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-16
        • 2016-01-16
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多